subprocess模块

Posted python包拯

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了subprocess模块相关的知识,希望对你有一定的参考价值。

os.system():输出结果到屏幕上,返回输出命令的状态,结果为0表示输出正确

 

 

os.popen()保存输出的结果

 

 

import subprocess #这个模块是为了替换一些老的模块,比如os.system等,通常在linux下比较好用一些

 

subprocess.call()

 

上面的例子说明,如果不涉及管道,直接用列表的形式就可以完成,否则得加上shell=True参数

subprocess.check_call():#检查返回状态

subprocess.getstatusoutput()#返回状态和结果

subprocess三种状态。stdout,stdin,stderr

>>>res=subprocess.Popen("ifconfig|grep192",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE)

>>> res.stdout.read()

\'inet addr:192.168.1.210 Bcast:192.168.1.255 Mask:255.255.255.0\\n\'

针对上面的命令,要读出结果,就得用res.stdout.read()格式

也可以读出错误

res.poll()可以返回状态,0表示命令执行正确

 

res.terminate()可以杀死res进程

下面的句子中,可以加入cwd:用于设置子进程的当前目录,env用于设置子进程的环境变量

>>>res=subprocess.Popen("sleep6;echo\'hello\'",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPEcwd=”/tmp”)

 

以上是关于subprocess模块的主要内容,如果未能解决你的问题,请参考以下文章

subprocess模块

subprocess模块

subprocess模块

subprocess模块

python的subprocess模块

subprocess模块