Python Subprocess

subprocess 包主要的功能是执行外部的命令和程序。比如使用wget下载文件,Ipconfig显示ip地址,subprocess的功能与shell类似。

主要有3个常用方法:

subprocess.run(["ls","-l"])

subprocess.call("ls -l", shell=True)

subprocess.Popen()

subprocess.getoutput("ls -l")

 


subprocess常用的封装函数:

当我们运行python的时候,都是在创建并允许一个进程,一个进程可以Fork一个子进程,并让这个子进程exec另外一个程序。

使用subprocess包中的函数创建子进程的时候,要注意:
1)在创建子进程后,父进程是否暂停,并等待子进程运行。

2)函数返回什么

3)当returncode不为0时,父进程如何处理。

 

subprocess.call()

父进程等待子进程完成

返回退出信息(returncode,相当于esxi_code)

 

subprocess.check_call()

父进程等待子进程完成

返回0,检查退出信息,如果returncode不为0,则举出错误subprocess.calledprocesserror,该对象包含有returncode属性,可用try...except...来检查。

 

subprocess.check_output()

父进程等待子进程完成

返回子进程向标准输出的输出结果

检查退出信息,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含有returncode属性和output属性,output属性为标准输出的输出结果,可用try...except...来检查。

 

Popen()

实际上,我们上面的三个函数都是基于Popen()的封装(wrapper)。这些封装的目的在于让我们容易使用子进程。当我们想要更个性化我们的需求的时候,就要转向Popen类,该类生成的对象用来代表子进程。

 

Popen.communicate(input=None)

  Interact with process: Send data to stdin.  Read data from stdout and stderr, until end-of-file is reached.  Wait for process to terminate. The optional input argument should be a string to be sent to the child process, orNone, if no data should be sent to the child.

  communicate() returns a tuple (stdoutdata, stderrdata).

 

此外,你还可以在父进程中对子进程进行其它操作,比如我们上面例子中的child对象:

child.wait()       # 等待子进程结束

child.poll()           # 检查子进程状态

child.kill()           # 终止子进程

child.send_signal()    # 向子进程发送信号

child.terminate()      # 终止子进程

stdout=subprocess.PIPE  保存输出结果

stdout.read()           # 读取正确的输出结果

stderr=subprocess.PIPE  保存错误结果

stderr.read()      # 读取错误的输出结果

 

示例1: stdout.read()

 

 

示例2: communicate

import subprocess

proc = subprocess.Popen(["ipconfig", "/all"], stdout=subprocess.PIPE)
out, err = proc.communicate()
print(out.decode("gbk"))

>>>
Windows IP 配置

   主机名  . . . . . . . . . . . . . : s01244
   主 DNS 后缀 . . . . . . . . . . . : 
   节点类型  . . . . . . . . . . . . : 对等
   IP 路由已启用 . . . . . . . . . . : 否
   WINS 代理已启用 . . . . . . . . . : 否

示例3: 实现多个子进程

def run_process(address):
    proc = subprocess.Popen(["ping", address], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    return proc

procs = []
address_list = ["baidu.com", "www.sina.com", "qq.com"]
for address in address_list:
    proc = run_process(address=address)
    procs.append(proc)

for proc in procs:
    out, err = proc.communicate()
    print(out.decode("gbk"))

 

posted @ 2016-12-09 19:22  Vincen_shen  阅读(229)  评论(0)    收藏  举报