subprocess的一些用法总结(不记得转载地址了)
2015-12-23 10:42
344 查看
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)
相关文章推荐
- 1035. 插入与归并(25)
- erlang虚拟机代码执行原理
- HDU-1271-整数对
- 【转载】网络
- Linux的作业管理(&、[ctrl+z]、jobs、fg、bg、kill)的使用
- Swift String 一些常用方法
- FullCalendar日历插件应用之数据展现(一)
- maven 添加OJDBC.jar到本地仓库
- MYSQL错误代码大全
- 构造方法的特点
- Delphi字符串分割使用Tstringlist示例
- 2015年最受开发者好评的混合应用UI框架大比拼
- 最短路之单源最短路
- 字节数组流转换成图片保存在项目的相对路径下
- 常见的伪随机数产生
- OC学习篇之-----类目·延展·协议之--延展
- ubuntu 安装 jdk1.7
- 构思一个在windows下仿objc基于动画层ui编程的ui引擎
- 说说Statement、PreparedStatement和CallableStatement的异同(转)
- Eclipse快捷键大全