1

I am trying to assign the return value of python --version to a variable using the code below.:

#! /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 

The output I'm getting is :

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

Please let me know what I am missing.

Thanks in advance.

2
  • 2
    You know you can get it via sys.version_info, right? Commented Jul 9, 2015 at 13:47
  • also select the tick mark near to the answer that gave you a desired output. this is how you should accept an answer Commented Jul 9, 2015 at 14:02

1 Answer 1

4

Python writes its version information to stderr (variable error, in your code) - like most other products.

Nothing was written to stdout. You will notice that the variable ver was printed, it was an empty string.

You also failed to direct stderr:

output = subprocess.Popen(["python --version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) 
Sign up to request clarification or add additional context in comments.

5 Comments

Because you did not direct stderr to PIPE
modified the code as output = subprocess.Popen(["python --version"],stderr= subprocess.PIPE, shell=True) (ver,error)= output.communicate() print "python is:",error and got the desired output.
Please note the comment made by @johnrsharpe
@johnrsharpe actually my intent is to check the version of python and if not correct want to install the desired version.
@cdarke thanks much for your inputs; it worked for me when i printed the error value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.