python 执行命令并获取输出_python2.7 调用外部命令并获取输出

python2.7 调用外部命令并获取输出

利用subprocess模块执行外部命令,并获取输出。

import subprocess

p = subprocess.Popen(['docker', 'inspect', 'f37ea0324351'],

stdout=subprocess.PIPE,

stderr=subprocess.PIPE)

(result, error) = p.communicate()

retcode = p.returncode

print("stdout =[" + result + "]\n")

print("stderr =[" + error + "]\n")

print("retcode =[" + str(retcode) + "]\n")

关于communicate()的说明,文档上是这样描述的:

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, or None, if no data should be sent to the child.

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

Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.

所以:

如果 p = subprocess.Popen([...], stdout=subprocess.PIPE, stderr=None)

那么(result, error) = p.communicate()就不能拿到外部命令的stderr输出,此时变量error的值就是None,而外部命令的错误就输出到stderr去了。

如果 p = subprocess.Popen([...], stdout=None, stderr=None)

那么(result, error) = p.communicate()就不能拿到外部命令的stdout和stderr输出,此时变量result和error的值就都是None。

如果 p = subprocess.Popen([...], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

那么(result, error) = p.communicate()也不能拿到外部命令的stderr输出,此时变量error的值就是None,而result的值包含外部命令的标准输出和标准错误内容。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值