版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tiantao2012/article/details/87179214
python在2.4版本后引入subprocess来管理子进程,简单来说就是可以调用外部程序,取代之前os.system,os.spawn等旧的的方法
其中subprocess提供了多种方法来执行子进程,分别是subprocess.call
subprocess.check_all
subprocess.check_output
subprocess.Popen
>>> retcode=subprocess.call(["ls","-al"])
total 1865448
drwxr-xr-x 30 tiantao User 4096 2月 12 20:22 .
drwxr-xr-x 204 root root 4096 1月 14 14:10 ..
-rw-r--r-- 1 tiantao User 234911 1月 2 18:59 after
drwx------ 4 tiantao User 4096 9月 15 2017 .ansible
-rw------- 1 tiantao User 0 3月 2 2018 .ansible_galaxy
>>> print retcode
0
>>>
上面语句可以看到和直接执行ls -al的结果是一样的,直接输出ls -al的执行结果,并且ls -al结果为零,类似于shell中的$?
例如原本在shell中的语句
output=`mycmd myarg`
# becomes
output = check_output(["mycmd", "myarg"])
output=`dmesg | grep hda`
# becomes
output=check_output("dmesg | grep hda", shell=True)
status = os.system("mycmd" + " myarg")
# becomes
status = subprocess.call("mycmd" + " myarg", shell=True)
或者这个来判断命令执行后的返回值
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
使用Popen可以替代os.spwalp
pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
==>
pid = Popen(["/bin/mycmd", "myarg"]).pid
os.spawnvp(os.P_NOWAIT, path, args)
==>
Popen([path] + args[1:])