如何从subprocess.Popen运行的进程中获取返回值?

时间:2015-07-09 13:46:03

标签: python python-2.7

我正在尝试使用以下代码将python --version的返回值分配给变量。:

#! /usr/bin/env python

import os
import sys
import subprocess
os.system('pwd')
print ("check the version of python")
output = subprocess.Popen(["python --version"], stdout=subprocess.PIPE, shell=True)
(ver, error)= output.communicate()
print "python is:",ver

我得到的输出是:

/home/mobaxterm/Desktop/mypy
check the version of python
Python 2.7.10
python is:

请让我知道我错过了什么。

提前致谢。

1 个答案:

答案 0 :(得分:2)

Python将其版本信息写入代码中的stderr(变量error) - 与大多数其他产品一样。

没有任何内容写入stdout。你会注意到变量ver 打印的,它是一个空字符串。

您也未能指示stderr

output = subprocess.Popen(["python --version"], stdout=subprocess.PIPE, 
             stderr=subprocess.PIPE, shell=True)