subprocess的一些用法总结(不记得转载地址了)

import subprocess

subprocess.call(['ls', '-1'], shell=True) #call类似于os.system()执行外部命令,而且他也支持定义的变量比如echo $HOME' subprocess.check_call(['false']) #这个false命令会返回一个exitcode不为0的结果,她会被捕捉raise output = subprocess.check_output(['ls', '-1']) #捕获执行结果输出 print 'Have %d bytes in output' % len(output) output = subprocess.check_output( 'echo to stdout; echo to stderr 1>&2; exit 1', #因为重定向了输出,输出流数据不被记录,错误输出流被记录 shell=True, ) output = subprocess.check_output( 'echo to stdout; echo to stderr 1>&2; exit 1', shell=True, stderr=subprocess.STDOUT, #错误输出也被重定向,只会打印check捕捉到的退出代码不是0的异常 ) print 'Have %d bytes in output' % len(output) print output print '\nread:' proc = subprocess.Popen(['echo', '"to stdout"'], Popen类似于os.popen,将输出,输入,错误定向到管道 stdout=subprocess.PIPE, #将输出流定向到管道 ) stdout_value = proc.communicate()[0] #获取数据 print '\tstdout:', repr(stdout_value) import subprocess

print '\nwrite:' proc = subprocess.Popen(['cat', '-'], stdin=subprocess.PIPE, #输入流定向到管道 ) proc.communicate('\tstdin: to stdin\n') print '\npopen2:'

proc = subprocess.Popen(['cat', '-'], stdin=subprocess.PIPE, #同时定向输出输入流 stdout=subprocess.PIPE, ) stdout_value = proc.communicate('through stdin to stdout')[0] print '\tpass through:', repr(stdout_value) print '\npopen3:' proc = subprocess.Popen('cat -; echo "to stderr" 1>&2', shell=True, stdin=subprocess.PIPE, ##同时定向输出输入错误流 stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) stdout_value, stderr_value = proc.communicate('through stdin to stdout') print '\tpass through:', repr(stdout_value) print '\tstderr :', repr(stderr_value) print '\npopen4:' proc = subprocess.Popen('cat -; echo "to stderr" 1>&2', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, #把错误流定向到输出流,那么错误流就是none ) stdout_value, stderr_value = proc.communicate('through stdin to stdout\n') print '\tcombined output:', repr(stdout_value) print '\tstderr value :', repr(stderr_value)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值