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的值包含外部命令的标准输出和标准错误内容。