Python之子进程subprocess模块
http://www.cnblogs.com/vamei/archive/2012/09/23/2698014.html
http://blog.csdn.net/jgood/article/details/4498166
http://docs.python.org/library/subprocess
subprocess.call()
[root@typhoeus79 20130925]# more test.py
#!/usr/bin/env python2.7
#-*- coding:utf8 -*- import subprocess rc = subprocess.call(["ls","-l"]) print "rc = ",rc
[root@typhoeus79 20130925]# ./test.py
total 4
-rwxr-xr-x 1 root root 118 Sep 25 11:18 test.py
rc = 0
将程序名ls和其对应的参数放在一个list中传给subprocess.call()
通过一个shell来解释字符串
[root@typhoeus79 20130925]# ./sub_shell.py
total 4
-rwxr-xr-x 1 root root 125 Sep 25 11:22 sub_shell.py
rc = 0
[root@typhoeus79 20130925]# more sub_shell.py
#!/usr/bin/env python2.7
#-*- coding:utf8 -*- import subprocess rc = subprocess.call("ls -l",shell=True) print "rc = ",rc
使用shell=True这个参数,使用字符串而不是使用list来运行子进程。python先运行一个shell,然后这个shell来解释整个字符串
Popen
基于Popen()的封装(wrapper),这些封装的目的在于让我们容易使用子进程。当我们想要更个性化我们的需求的时候,就要转向Popen类,该类生成的对象用来代表子进程
Using the subprocess module
===========================
This module defines one class called Popen: class Popen(args, bufsize=0, executable=None,
stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=False, shell=False,
cwd=None, env=None, universal_newlines=False,
startupinfo=None, creationflags=0):
[root@typhoeus79 20130925]# ./sub_popen.py
parent process
<subprocess.Popen object at 0x7fed17542050>
[root@typhoeus79 20130925]# PING www.a.shifen.com (220.181.111.148) 56(84) bytes of data. --- www.a.shifen.com ping statistics ---
5 packets transmitted, 0 received, 100% packet loss, time 4002ms [root@typhoeus79 20130925]# more sub_popen.py
#!/usr/bin/env python26
#-*- coding:utf8 -*- import subprocess child = subprocess.Popen(["ping","-c","","www.baidu.com"])
#child = subprocess.Popen("ping -c5 www.baidu.com",shell=True) print("parent process")
print child
父进程在开启子进程之后没有等到其完成,而是直接print
改成等待模式:
[root@typhoeus79 20130925]# ./sub_popen.py
PING www.a.shifen.com (220.181.112.143) 56(84) bytes of data. --- www.a.shifen.com ping statistics ---
5 packets transmitted, 0 received, 100% packet loss, time 4001ms parent process
<subprocess.Popen object at 0x7fe424c34050>
[root@typhoeus79 20130925]# more sub_popen.py
#!/usr/bin/env python26
#-*- coding:utf8 -*- import subprocess child = subprocess.Popen(["ping","-c","","www.baidu.com"]) child.wait()
print("parent process")
print child
父进程中对子进程进行其他操作:
child.poll() #检查子进程状态
child.kill() #终止子进程
child.send_signal() #向子进程发送信号
child.terminate() #终止子进程
子进程的PID存储在child.pid中
子进程的文本流控制
子进程的标准输入、标准输出、标准错误通过如下属性:
{'_child_created': True, 'returncode': 1, 'stdout': None, 'stdin': None, 'pid': 7070, 'stderr': None, 'universal_newlines': False}
child.stdin
child.stdout
child.stderr
可以在Popen()建立子进程的时候改变标准输入、标准输出和标准错误,并可以利用subprocess.PIPE将多个子进程的输入和输出在一起,构成管道pipe:
[root@typhoeus79 20130925]# more sub_pipe.py
#!/usr/bin/env python26
#-*- coding:utf8 -*- import subprocess child1 = subprocess.Popen(["ls","-l"],stdout=subprocess.PIPE) child2 = subprocess.Popen(["wc"],stdin=child1.stdout,stdout=sub
process.PIPE) out = child2.communicate() print out
[root@typhoeus79 20130925]# ./sub_pipe.py
(' 4 29 167\n', None)
1、child1的stdout将文本输出缓存到subprocess.PIPE中
2、child2的stdin从child1的stdout读取文本
3、child2的输出文本也被存储在subprocess.PIPE中
4、communicate()方法从PIPE中读取相应的文本
communicate是Popen对象的一个方法,该方法会阻塞父进程,直到子进程完成。
communicate(input=None)
Interact with process: Send data to stdin. Read data from stdout
and stderr, until end-of-file is reached. Wait for process to
terminate. The optional input argument should be a string to be
sent to the child process, or None, if no data should be sent to
the child. communicate() returns a tuple (stdout, stderr). Note: The data read is buffered in memory, so do not use this
method if the data size is large or unlimited.
可以使用communicate()方法使用PIPE给子进程输入:
#!/usr/bin/env python26
#-*- coding:utf8 -*- import subprocess
import time child = subprocess.Popen(["cat"],stdin=subprocess.PIPE) time.sleep(5)
child.communicate("Hello\n")
通过time.sleep也可以看到communicate是阻塞父进程
对python执行系统命令的封装
def sys_command(system_cmd):
logger.debug("system_cmd = '%s'." %system_cmd)
pipe = subprocess.Popen(system_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True,stdin=subprocess.PIPE) stdout, stderr = pipe.communicate()
returncode = pipe.returncode logger.debug("returncode = '%d'." %returncode)
logger.debug("stdout = '%s'." %stdout)
logger.debug("stderr = '%s'." %stderr) return returncode,stdout,stderr
Python之子进程subprocess模块的更多相关文章
- python笔记之subprocess模块
python笔记之subprocess模块 [TOC] 从Python 2.4开始,Python引入subprocess模块来管理子进程,以取代一些旧模块的方法:如 os.system.os.spaw ...
- Python中的subprocess模块
Subprocess干嘛用的? subprocess模块是python从2.4版本开始引入的模块.主要用来取代 一些旧的模块方法,如os.system.os.spawn*.os.popen*.comm ...
- python学习之-- subprocess模块
subprocess 模块 功能:用来生成子进程,并可以通过管道连接它们的输入/输出/错误,以及获得它们的返回值.它用来代替多个旧模块和函数: os.system os.spawn* os.popen ...
- Python中使用subprocess模块远程执行命令
使用subprocess模块执行远程命令 服务端代码 1 import socket 2 import subprocess 3 4 sh_server = socket.socket() 5 sh_ ...
- python学习之subprocess模块
subprocess.Popen 这个模块主要就提供一个类Popen: class subprocess.Popen( args, bufsize=0, executable=None, stdin= ...
- random模块、os模块、序列化模块、sy模块s、subprocess模块
random随机数模块 random.random( ) 随机产生一个0-1之间的小数 print(random.random()) # 0.31595547439342897 random.rand ...
- Python subprocess模块学习总结
从Python 2.4开始,Python引入subprocess模块来管理子进程,以取代一些旧模块的方法:如 os.system.os.spawn*.os.popen*.popen2.*.comman ...
- 子进程管理模块subprocess
subprocess模块允许你生成子进程,连接管道,并获取返回的代码. 一.使用subprocess模块 模块中定义了一个Popen类: subprocess.Popen(args, bu ...
- Python学习笔记——基础篇【第六周】——Subprocess模块
执行系统命令 可以执行shell命令的相关模块和函数有: os.system os.spawn* os.popen* --废弃 popen2.* --废弃 com ...
随机推荐
- mysql explain 分析sql语句
鉴于最近做的事情,需要解决慢sql的问题,现补充一点sql语句性能分析之explain的使用方式! 综合返回数据情况,分析各个参数,可以了解sql 使用方法:explain + sql语句 如 :e ...
- PS+HTML测试
PS: 1. 写出标尺.参考线.网格线.放大和缩小的快捷键 2. 写出RGB模式和CMYK颜色模式里每一个字母代表什么颜色 3. 写出暖色和冷色各3种 4. 写出常用的抠图工具(6个以上) 5. 写出 ...
- iOS将自己的框架更新到cocopods上
第一步 把自己的框架更新到github 上,为了提交地址给他人下载.这里就不详细介绍如何把项目更新到github上了 第二步 这个时候我们的项目已经挂在github上了我们需要给本地的项目新建一个Po ...
- PHP 支付
蚂蚁金服开放平台 2.下载PHP的SDK&demo 3.申请应用 OR 使用沙箱环境 4.生成应用私钥&应用公钥 5.配置config.php 蚂蚁金服开放平台",对,没错, ...
- JPA + SpringData 操作数据库原来可以这么简单 ---- 深入了解 JPA - 1
原创播客,如需转载请注明出处.原文地址:http://www.cnblogs.com/crawl/p/7703679.html ------------------------------------ ...
- 剖析Prometheus的内部存储机制
Prometheus有着非常高效的时间序列数据存储方法,每个采样数据仅仅占用3.5byte左右空间,上百万条时间序列,30秒间隔,保留60天,大概花了200多G(引用官方PPT). 接下来让我们看看他 ...
- SimpleDateFormat时间格式化存在线程安全问题
想必大家对SimpleDateFormat并不陌生.SimpleDateFormat 是 Java 中一个非常常用的类,该类用来对日期字符串进行解析和格式化输出,但如果使用不小心会导致非常微妙和难以调 ...
- 【ASP.NET MVC 学习笔记】- 11 Controller和Action(2)
本文参考:http://www.cnblogs.com/willick/p/3331513.html 1.MVC一个请求的发出至action返回结果的流程图如下: 重点是Controller Fact ...
- js修改title
document.title = 'xxxxxx';
- sublime text3 开发必备插件
1,Package Control 通俗易懂地说,这个是你在完成安装SublimeText后必须安装的东西.你问为什么?因为有了这个特殊的"插件包",你可以很容易地安装.升级.删除 ...