1、一般格式
cmdres = subprocess.Popen(cmdstr, shell = True
,stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
for i in cmdres.stdout.readlines():
print i
fi cmdres.returncode ! = 0
print 'error'
subprocess.PIPE
在创建Popen对象时,subprocess.PIPE可以初始化stdin, stdout或stderr参数,表示与子进程通信的标准流。
subprocess.STDOUT
创建Popen对象时,用于初始化stderr参数,表示将错误通过标准输出流输出。
Popen.returncode
获取进程的返回值。如果进程还没有结束,返回None。
Popen.returncode
子程序的返回值,由poll()或者wait()设置,间接地也由communicate()设置。
如果为None,表示子进程还没终止。
如果为负数-N的话,表示子进程被N号信号终止。(仅限*nux)
2、别人封装的方法,封装成commands的模式
def check_output(cmd):
''' execute a shell cmd and return a tuple of (exitcode,msg)
where msg could be stdoutdata or stderrdata depends on whether exitcode is 0 or not.
'''
popen = subprocess.Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
(stdoutdata, stderrdata) = popen.communicate()
retcode = popen.poll()
if retcode != 0:
return (retcode, stderrdata)
return (retcode, stdoutdata)
Popen
.communicate(input=None)
和子进程交互:发送数据到stdin,并从stdout和stderr读数据,直到收到EOF。等待子进程结束。可选的input如有有的话,要为字符串类型。
此函数返回一个元组: (stdoutdata
, stderrdata
) 。
注意,要给子进程的stdin发送数据,则Popen的时候,stdin要为PIPE;同理,要可以收数据的话,stdout或者stderr也要为PIPE。
注意:读到的数据会被缓存在内存里,所以数据量非常大的时候要小心了。