subprocess模块¶
subprocess.Popen¶
注解
类
构造函数常用参数:
args字符串或者参数序列。shell=False是否打开命令窗口执行命令行stdin=None可以取PIPE,文件句柄,文件描述符和Nonestdout=None可以取PIPE,文件句柄,文件描述符和Nonestderr=None可以取PIPE,文件句柄,文件描述符,STDOUT和None
重要
流对象为 None 时,子进程将继承父进程的标准流。
1 2 3 4 5 6 7 8 9 10 11 12 13 | #D:\hello_world.py
print hello,world
#D:\test_subprocess.py
from subprocess import *
# ``shell = True`` cannot be skipped, as it uses shell to run the command line
open_obj = Popen('hello_world.py', shell = True, stdout = PIPE)
# If you want to ignore ``shell`` parameter, you can use executable parameter as below:
# open_obj = Popen('python hello_world.py', stdout = PIPE)
out_obj = open_obj.communicate()
print open_obj[0]
|
Popen 实例¶
poll()子进程是否结束,返回returncode属性值wait()等待子进程结束,返回returncode属性值警告
构造
Popen对象时,不要使用PIPE参数,会死锁。communicate()阻塞式执行命令行,返回元组(stdoudata, stderrdata)。注解
要返回元组
(stdoudata, stderrdata),实例化时,必须设置stdout=PIPE; 要想将数据传递给子进程的输入流,必须设置stdin=PIPE。send_signal()发信号给子进程(SIGTERM)terminate()终止子进程kill()杀死子进程
注解
Windows 中 kill()/terminate() 一样,都是调用 Windows API:TerminateProcess;
Unix 中 terminate() 发送消息 SIGTERM, kill() 发送消息 SIGKILL
pid表示子进程的 ID;如果使用shell=True,则表示命令窗进程的 IDreturncodeNone表示子进程未结束;Unix 中,-N表示等待信号N结束子进程。stdout如果实例化时,设置stdout=PIPE,则stdout为子进程的输出流;否则为Nonestderr如果实例化时,设置stderr=PIPE,则stderr为子进程的错误流;否则为Nonestdin如果实例化时,设置stdin=PIPE,则stdin为子进程的输入流;否则为None
1 2 | open_obj = Popen('python hello_world.py', stdout=PIPE)
print open_obj.stdout.read()
|
subprocess 的便捷接口¶
call()阻塞式执行命令行,返回returncode属性值警告
不能设置参数 stdout=PIPE/stderr=PIPE,会死锁
check_call()阻塞式执行命令行,返回0,表示子进程正常退出; 否则抛出异常CalledProcessErrorcheck_output()阻塞式执行命令行,正常情况下返回命令行输出(字节数组); 否则抛出异常CalledProcessError注解
不能使用
stdout=PIPE,可以使用stderr=STDOUT来捕获并输出错误信息。