python subprocess 模块测试

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:])

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值