我正在尝试使用以下代码将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:
请让我知道我错过了什么。
提前致谢。
答案 0 :(得分:2)
Python将其版本信息写入代码中的stderr
(变量error
) - 与大多数其他产品一样。
没有任何内容写入stdout
。你会注意到变量ver
是打印的,它是一个空字符串。
您也未能指示stderr
:
output = subprocess.Popen(["python --version"], stdout=subprocess.PIPE,
stderr=subprocess.PIPE, shell=True)