17.1 subprocess
这个模块允许你产生子线程,连接他们(主线成,和产生的子线程)之间的输入/输出/错误 管道(pipes,管道是一种把两个进程之间的标准输入和标准输出连接起来的机制,从而提供一种让多个进程间通信的方法)。这个模块想要替换一些比较旧的模块和方法:
os.system
os.spawn*
os.popen*
popen2.*
commands.*
17.1.1 使用subprocess
在使用subprocess时推荐调用以下几个方来完成你的需求。如果有更高级的情况,可以使用Popen接口。
subprocess.cell(args, *, stdin=None, stdout=None, stderr=None, shell=False)
根据args参数运行命令,等待命令执行结束,返回进程返回值
>>>subprocess.call(["ls","-l"])
0
>>>subprocess.call("exit 1",shell=True)
1
subprocess.check_call(args,*,stdin=None,stdout=None,stderr=None,shell=False)
根据args参数运行命令,等待命令执行结束,如果进程返回值为0则返回(return),否则会raise一个CalledProcessError错误,CalledProcessError类的returncode属性会包含进程返回值。
>>>subprocess.check_call(["ls","-l"])
0
>>>subprocess.check_call("exit 1",shell=True)
Traceback (most recent call last):
...
subprocess.CalledProcessError:Command 'exit 1' returned non-zero exit status 1
subprocess.check_output(args,*,stdin=None,stderr=None,shell=False,universal_newlines=False)
正在更新....