python子进程模块subprocess详解与应用实例 之二
1.2. Popen 对象
Popen类的实例有下列方法:
1. Popen.poll()
检查子进程是否已经结束,设置并返回返回码值。
2. Popen.wait()
等待子进程结束,设置并返回返回码值。
WARNING: 当使用 stdout=PIPE 或 stderr=PIPE 并且子进程生成了足够多的输出信息到管道,以至于管道阻塞,将会造成死锁。
使用 communicate()可以避免这种情况。
3. Popen.communicate(input=None)
和子进程进行交互: 发送数据到stdin, 从stdout和 stderr读取数据,直到遇到 end-of-file。等待子进程结束。
可选的 input 参数是一个传送给子进程的字符串,或 None。
communicate() 返回一个元组(stdoutdata, stderrdata).
NOTE: 如果想发送数据到子进程的 stdin, 需要设置 stdin=PIPE并创建Popen对象。
相似的,要想获得返回结果元组中的非空值,需要设置 stdout=PIPE或 stderr=PIPE.
实际上,读取的数据是缓冲在内存中,因此,如果数据太大或无限时不要使用这个上方法。
4. Popen.send_signal(signal)
发送一个信号 signal到子进程。
NOTE: 在Windows中, SIGTERM是terminate()的别名。
5. Popen.terminate()
停止子程序,在Posix操作系统中,这个方法发送的是SIGTERM到子程序。
6. Popen.kill()
杀死子进程,在Posix操作系统中,这个上函数发送SIGKILL给子进程。
下面的属性也是同样有效的:
WARNING: 使用communicate()而不是 .stdin.write, .stdout.read 或 stderr.read,可以避免因管道阻塞而造成的死锁。
1. Popen.stdin
如果参数值为 PIPE, 那么这个属性值是一个文件对象,用来提供子进程的输入。
否则,它的值 为 None.
2. Popen.stdout
如果参数值为 PIPE, 那么这个属性值是一个文件对象,它提供了子进程的输出。
否则,值为 None
3. Popen.stderr
If the stderr argument was PIPE, this attribute is a file object that provides error output from the child process.
Otherwise, it is None.
4. Popen.pid
子进程的进程ID
Note that if you set the shell argument to True, this is the process ID of the spawned shell.
5. Popen.returncode
子进程的返回码,由poll()和wait()设置(并间接由 communicate()设置)。
非零值表示子进程还没有被结束。
负值 -N 表示子进程被信号N结束。
1.3. Windows Popen 使用
The STARTUPINFO class and following constants are only available on Windows.
1. class subprocess.STARTUPINFO
Partial support of the Windows STARTUPINFO structure is used for Popen creation.
2. dwFlags
A bit field that determines whether certain STARTUPINFO attributes are used when the process creates a window.
si = subprocess.STARTUPINFO()
si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
3. hStdInput
If dwFlags specifies STARTF_USESTDHANDLES, this attribute is the standard input handle for the process. If
STARTF_USESTDHANDLES is not specified, the default for standard input is the keyboard buffer.
4. hStdOutput
If dwFlags specifies STARTF_USESTDHANDLES, this attribute is the standard output handle for the process. Otherwise,
this attribute is ignored and the default for standard output is the console window’s buffer.
5. hStdError
If dwFlags specifies STARTF_USESTDHANDLES, this attribute is the standard error handle for the process. Otherwise,
this attribute is ignored and the default for standard error is the console window’s buffer.
6. wShowWindow
If dwFlags specifies STARTF_USESHOWWINDOW, this attribute can be any of the values that can be specified in the
nCmdShow parameter for the ShowWindow function, except for SW_SHOWDEFAULT. Otherwise, this attribute is ignored.
7. SW_HIDE is provided for this attribute. It is used when Popen is called with shell=True.
1.3.1. 常量
The subprocess module exposes the following constants.
subprocess.STD_INPUT_HANDLE
The standard input device. Initially, this is the console input buffer, CONIN$.
subprocess.STD_OUTPUT_HANDLE
The standard output device. Initially, this is the active console screen buffer, CONOUT$.
subprocess.STD_ERROR_HANDLE
The standard error device. Initially, this is the active console screen buffer, CONOUT$.
subprocess.SW_HIDE
Hides the window. Another window will be activated.
subprocess.STARTF_USESTDHANDLES
Specifies that the STARTUPINFO.hStdInput, STARTUPINFO.hStdOutput, and STARTUPINFO.hStdError attributes contain
additional information.
subprocess.STARTF_USESHOWWINDOW
Specifies that the STARTUPINFO.wShowWindow attribute contains additional information.
subprocess.CREATE_NEW_CONSOLE
The new process has a new console, instead of inheriting its parent’s console (the default).
This flag is always set when Popen is created with shell=True.
subprocess.CREATE_NEW_PROCESS_GROUP
A Popen creationflags parameter to specify that a new process group will be created.
This flag is necessary for using os.kill() on the subprocess
This flag is ignored if CREATE_NEW_CONSOLE is specified.
1.4. 使用 subprocess模块代替旧函数
In this section, “a becomes b” means that b can be used as a replacement for a.
Note All “a” functions in this section fail (more or less) silently if the executed program cannot be found;
the “b” replacements raise OSError instead.
In addition, the replacements using check_output() will fail with a CalledProcessError if the requested operation
produces a non-zero return code. The output is still available as the output attribute of the raised exception.
In the following examples, we assume that the relevant functions have already been imported from the subprocess
module.
1.4.1. Replacing /bin/sh shell backquote
output=`mycmd myarg`
# becomes
output = check_output(["mycmd", "myarg"])
1.4.2. Replacing shell pipeline
output=`dmesg | grep hda`
# becomes
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]
The p1.stdout.close() call after starting the p2 is important in order for p1 to receive a SIGPIPE if p2 exits before p1.
Alternatively, for trusted input, the shell’s own pipeline support may still be used directly:
output=`dmesg | grep hda`
# becomes
output=check_output("dmesg | grep hda", shell=True)
1.4.3. Replacing os.system()
status = os.system("mycmd" + " myarg")
# becomes
status = subprocess.call("mycmd" + " myarg", shell=True)
Notes:
Calling the program through the shell is usually not required.
A more realistic example would look like this:
try:
retcode = call("mycmd" + " myarg", shell=True)
if retcode < 0:
print >>sys.stderr, "Child was terminated by signal", -retcode
else:
print >>sys.stderr, "Child returned", retcode
except OSError as e:
print >>sys.stderr, "Execution failed:", e
1.4.4. Replacing the os.spawn family
P_NOWAIT example:
pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
==>
pid = Popen(["/bin/mycmd", "myarg"]).pid
P_WAIT example:
retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
==>
retcode = call(["/bin/mycmd", "myarg"])
Vector example:
os.spawnvp(os.P_NOWAIT, path, args)
==>
Popen([path] + args[1:])
Environment example:
os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
==>
Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}
1.4.5. Replacing os.popen(), os.popen2(), os.popen3()
pipe = os.popen("cmd", 'r', bufsize)
==>
pipe = Popen("cmd", shell=True, bufsize=bufsize, stdout=PIPE).stdout
pipe = os.popen("cmd", 'w', bufsize)
==>
pipe = Popen("cmd", shell=True, bufsize=bufsize, stdin=PIPE).stdin
(child_stdin, child_stdout) = os.popen2("cmd", mode, bufsize)
==>
p = Popen("cmd", shell=True, bufsize=bufsize,
stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdin, child_stdout) = (p.stdin, p.stdout)
(child_stdin,
child_stdout,
child_stderr) = os.popen3("cmd", mode, bufsize)
==>
p = Popen("cmd", shell=True, bufsize=bufsize,
stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
(child_stdin,
child_stdout,
child_stderr) = (p.stdin, p.stdout, p.stderr)
(child_stdin, child_stdout_and_stderr) = os.popen4("cmd", mode,
bufsize)
==>
p = Popen("cmd", shell=True, bufsize=bufsize,
stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
On Unix, os.popen2, os.popen3 and os.popen4 also accept a sequence as the command to execute, in which case arguments
will be passed directly to the program without shell intervention. This usage can be replaced as follows:
(child_stdin, child_stdout) = os.popen2(["/bin/ls", "-l"], mode,
bufsize)
==>
p = Popen(["/bin/ls", "-l"], bufsize=bufsize, stdin=PIPE, stdout=PIPE)
(child_stdin, child_stdout) = (p.stdin, p.stdout)
Return code handling translates as follows:
pipe = os.popen("cmd", 'w')
...
rc = pipe.close()
if rc is not None and rc >> 8:
print "There were some errors"
==>
process = Popen("cmd", 'w', shell=True, stdin=PIPE)
...
process.stdin.close()
if process.wait() != 0:
print "There were some errors"
1.4.6. Replacing functions from the popen2 module
(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
==>
p = Popen("somestring", shell=True, bufsize=bufsize,
stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)
On Unix, popen2 also accepts a sequence as the command to execute, in which case arguments will be passed directly to
the program without shell intervention. This usage can be replaced as follows:
(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize,mode)
==>
p = Popen(["mycmd", "myarg"], bufsize=bufsize,
stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)
popen2.Popen3 and popen2.Popen4 basically work as subprocess.Popen, except that:
Popen raises an exception if the execution fails.
the capturestderr argument is replaced with the stderr argument.
stdin=PIPE and stdout=PIPE must be specified.
popen2 closes all file descriptors by default, but you have to specify close_fds=True with Popen.
1.5. NOTES
1.5.1. Converting an argument sequence to a string on Windows
On Windows, an args sequence is converted to a string that can be parsed using the following rules (which correspond
to the rules used by the MS C runtime):
Arguments are delimited by white space, which is either a space or a tab.
A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space
contained within. A quoted string can be embedded in an argument.
A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark.
Backslashes are interpreted literally, unless they immediately precede a double quotation mark.
If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal
backslash. If the number of backslashes is odd, the last backslash escapes the next double quotation mark as
described in rule 3.
from:http://blog.chinaunix.net/uid-26000296-id-4461541.html
python子进程模块subprocess详解与应用实例 之二的更多相关文章
- python子进程模块subprocess详解与应用实例 之三
二.应用实例解析 2.1 subprocess模块的使用 1. subprocess.call >>> subprocess.call(["ls", " ...
- python子进程模块subprocess详解与应用实例 之一
subprocess--子进程管理器 一.subprocess 模块简介 subprocess最早是在2.4版本中引入的. subprocess模块用来生成子进程,并可以通过管道连接它们的输入/输出/ ...
- python子进程模块subprocess详解
subprocess--子进程管理器一.subprocess 模块简介subprocess最早是在2.4版本中引入的.subprocess模块用来生成子进程,并可以通过管道连接它们的输入/输出/错误, ...
- python之模块datetime详解
# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之模块datetime详解 import datetime #data=datetime.dat ...
- Python Deque 模块使用详解,python中yield的用法详解
Deque模块是Python标准库collections中的一项. 它提供了两端都可以操作的序列, 这意味着, 你可以在序列前后都执行添加或删除. https://blog.csdn.net/qq_3 ...
- python——pickle模块的详解
pickle模块详解 该pickle模块实现了用于序列化和反序列化Python对象结构的二进制协议. “Pickling”是将Python对象层次结构转换为字节流的过程, “unpickling”是反 ...
- Python编程之子进程管理(subprocess)详解
引言 在写程序时,我们无法避免需要运行外部程序,相较于功能比较简单的os.system(),更加倾向于使用subprocess模块来执行外部程序. 模块介绍 subprocess.run() 使用su ...
- python datetime模块参数详解
Python提供了多个内置模块用于操作日期时间,像calendar,time,datetime.time模块,它提供 的接口与C标准库time.h基本一致.相比于time模块,datetime模块的接 ...
- python re模块findall()详解
今天写代码,在写到郑泽的时候遇到了一个坑,这个坑是re模块下的findall()函数. 下面我将结合代码,记录一下 import re string="abcdefg acbdgef abc ...
随机推荐
- Android快速开发-选项卡
介绍 几行代码实现Android选项卡界面,支持标准底部Tab自定义视图选项卡,头部文字选项卡. 底部自定义视图选项卡 先来看看实现下图中的效果我们代码应该怎么写? 实现上图效果只需以下代码: pub ...
- canvas实现点击带水纹的按钮
咱今天在闲逛网页时,看到一个点击带水纹的按钮特效,尼玛,写的还挺好,先看效果: 于是就奔着升级版的拿来主义,别人的好东西,咱都要拿来滴,so,扒代码! 完整代码在最后,是经过我的改进优化滴. 在这里先 ...
- 人生苦短之我用Python篇(深浅拷贝、常用模块、内置函数)
深浅拷贝 有时候,尤其是当你在处理可变对象时,你可能想要复制一个对象,然后对其做出一些改变而不希望影响原来的对象.这就是Python的copy所发挥作用的地方. 定义了当对你的类的实例调用copy.c ...
- C# 报警 控制蜂鸣器发声
在C#中可以通过以下四种方式来实现蜂鸣或者报警,播放声音之类的功能.XP下对蜂鸣有用,win7下请接上扬声器. 1). Beep的报警实现 [c-sharp] view plaincopy / ...
- [Luogu4390][BOI2007]Mokia 摩基亚
luogu 题意 支持平面内单点加一个值以及矩阵求和. 平面大小\(W\le2*10^6\),修改操作\(\le1.6*10^5\),查询操作\(\le10^4\) sol \(CDQ\)写一发. 把 ...
- HTML`CSS_网站页面不同浏览器兼容性问题解决
目前,最为流行的浏览器共有五个:分别是ie,Edge浏览器(属于微软),火狐,谷歌(chrome)Safari和Opera五大浏览器. Trident内核:IE ,360,,猎豹,百度: Gecko内 ...
- 利用git bash和git gui向git远程仓库提交文件
1.首先在该文件夹下git init 2.然后在github下面创建一个新仓库去存储你的代码 3.然后利用add添加远程仓库 4.然后点击stage changed 5.最后点击长传 参考链接:htt ...
- xcomponent web 跨域组件介绍
1. 项目地址: https://github.com/krakenjs/xcomponent 2. 支持的特性 a. Render an iframe or popup on a different ...
- 设置正确的DNS
上网或下载软件慢问题,除去少数设备陈旧.感染病毒.网卡硬件故障和网卡驱动错误方面的因素,绝大部分原因是由于部分上网电脑或家用无线路由器设置了错误的DNS造成的,正确的方法是应该在电脑或路由器上使用本地 ...
- WebService简单实现
1. WebService SOAP.WSDL.UDDISOAP(Simple Object Access Protocal,简单对象访问协议),是在分散或在分布式环境中交换信息的简单协议.WSDL( ...