python subprocess模块以及communication方法
目的:
subprocess 是可以创建一个进程去执行其他的程序,并与之进行交互:将数据发送到标准输入。
communication() 返回一个元组(out, err)。数据流以文本模式打开,为字符串格式,否则为字节
import subprocess
try:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)
out, err = p.communication(timeout=3)
return p.returncode, out.decode('utf-8'), err.decode('utf-8')
exception Exception:
p.kill()
p.terminate()
return None, None, None
进程在timeout之后没有终止,则会引发TimeoutExpired异常。