从Python 2.4开始,Python引入subprocess模块来管理子进程,以取代一些旧模块的方法:如 os.system、os.spawn*、os.popen*、popen2.*、commands.*不但能够调用外部的命令做为子进程,并且能够链接到子进程的input/output/error管道,获取相关的返回信息html
运行python的时候,咱们都是在建立并运行一个进程。像Linux进程那样,一个进程能够fork一个子进程,并让这个子进程exec另一个程序。在Python中,咱们经过标准库中的subprocess包来fork一个子进程,并运行一个外部的程序。
subprocess包中定义有数个建立子进程的函数,这些函数分别以不一样的方式建立子进程,因此咱们能够根据须要来从中选取一个使用。另外subprocess还提供了一些管理标准流(standard stream)和管道(pipe)的工具,从而在进程间使用文本通讯。python
subprocess以及经常使用的封装函数shell
1)Popen启动新的进程与父进程并行执行,默认父进程不等待新进程结束。windows
import subprocesscurl
def TestPopen():
p=subprocess.Popen("dir",shell=True)
for i in range(10) :
print "other things: %d"%i
TestPopen()ide
2)p.wait函数使得父进程等待新建立的进程运行结束,而后再继续父进程的其余任务。且此时能够在p.returncode中获得新进程的返回值。函数
import subprocess
child = subprocess.Popen(["ping","www.baidu.com"])
child.wait()
print("parent process")工具
3) p.poll函数能够用来检测新建立的进程是否结束。url
import subprocess
import datetime
import timespa
def TestPoll():
print (datetime.datetime.now())
p=subprocess.Popen(["ping","www.baidu.com"],shell=True)
t = 1
while(t <= 3):
if(p.poll()==None):
print (p.returncode)
break
t+=1
print (datetime.datetime.now())
TestPoll()
4) p.kill或p.terminate用来结束建立的新进程,在windows系统上至关于调用TerminateProcess(),在posix系统上至关于发送信号SIGTERM和SIGKILL。
import subprocess import time def TestKillAndTerminate(): p=subprocess.Popen("notepad.exe") t = 1 while(t <= 5): time.sleep(1) t +=1 p.kill() #p.terminate() print ("new process was killed") TestKillAndTerminate()
5) p.communicate能够与新进程交互,可是必需要在popen构造时候将管道重定向。(要注意的是,communicate()是Popen对象的一个方法,该方法会阻塞父进程,直到子进程完成。)
def TestCommunicate(): cmd = "dir" p=subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) (stdoutdata, stderrdata) = p.communicate() print (stdoutdata) print ">>>>>>>>>>>>>>>>>>>>>>" if p.returncode != 0: print (cmd + "error !") #defaultly the return stdoutdata is bytes, need convert to str for r in str(stdoutdata).split("\n"): print (r) print (p.returncode) def TestCommunicate2(): cmd = "dir" #universal_newlines=True, it means by text way to open stdout and stderr p = subprocess.Popen(cmd, shell=True, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) curline = p.stdout.readline() while(curline != ""): print (curline) curline = p.stdout.readline() p.wait() print (p.returncode) TestCommunicate() TestCommunicate2()
6) call函数能够认为是对popen和wait的封装,直接对call函数传入要执行的命令行,将命令行的退出code返回。
import subprocess def TestCall(): retcode = subprocess.call("dir",shell=True) print (retcode) TestCall()
7)总结
popen的参数,第一个为字符串(或者也能够为多个非命名的参数),表示你要执行的命令和命令的参数;后面的均为命名参数;shell=True,表示你前面的传入的命令将在shell下执行,若是你的命令是个可执行文件或bat,不须要指定此参数;stdout=subprocess.PIPE用来将新进程的输出重定向,stderr=subprocess.STDOUT将新进程的错误输出重定向到stdout,stdin=subprocess.PIPE用来将新进程的输入重定向;universal_newlines=True表示以text的方式打开stdout和stderr。
其余的不推荐使用的模块:
os.system
os.spawn*
os.popen*
popen2.*
commands.*
参考:
http://www.liuzhongshu.com/code/subprocess-detail.html
http://www.liuzhongshu.com/code/python-vs-bat.html
subprocess.call, subprocess.check_call(), subprocess.check_output()
subprocess.Popen(), subprocess.PIPE
Popen.wait(), Popen.communicate()
subprocess.call, subprocess.check_call(), subprocess.check_output()
subprocess.Popen(), subprocess.PIPE
Popen.wait(), Popen.communicate()