好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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.PIPE,cwd=”/tmp”)

以上就是subprocess模块的详细介绍的详细内容,更多请关注Gxl网其它相关文章!

查看更多关于subprocess模块的详细介绍的详细内容...

  阅读:32次