3

I am working on the below code.

#!/usr/bin/python

import subprocess
import os

cmd =  'python --version'
stdout = subprocess.Popen(cmd, shell = True, stdout = subprocess.PIPE).stdout
ver = stdout.read()

This code is simply printing the python version on the console and the variable ver is not getting any value. Can anyone please help me understand why this is not working?

I had similar code where i am checking whether a process is running on the node or not.

cmd =  'ps -ef | grep cmserver | grep -v grep'
stdout = subprocess.Popen(cmd, shell = True, stdout = subprocess.PIPE).stdout
cmserver = stdout.read()

And here, nothing is printed on the screen and the variable cmserver has the required value.

2
  • 3
    You are unhappy with sys.version_info? Commented May 10, 2016 at 7:49
  • No, the thing is I wanted to understand this behavior difference. I was surprised to see such a thing happening. I am very well ok with sys.version_info as it serves my purpose. But it cant satisfy the curiosity :) Commented May 10, 2016 at 8:11

3 Answers 3

5

It's because Python prints the version string out onto stderr, not stdout. So, the fix is minor:

process = subprocess.Popen(cmd, shell = True,
                           stdout = subprocess.PIPE,
                           stderr = subprocess.PIPE)
version = process.stderr.read()

But as @polku says, this solution is kind of kludgy. A more direct Python-language mechanism to get the version would be better, such as the one he/she mentions.

Sign up to request clarification or add additional context in comments.

2 Comments

but why to stderr?
@Gauranga that is sort of a standard thing, not particular to the python executable. For programs that are expected to generate a lot of output, it helps to separate metadata like that to another stream. That's how I've always understood it, anyway. There may be a more formally documented reason out there. gcc does the same thing.
4

I don't know why it's not working but if you just want the python version you can simply

import sys
print(sys.version_info)

It's a tuple, you can access the different elements by indexing.

Edit: it's actually a named tuple you can also write sys.version_info.major, it's probably better.

Comments

0
cmd =  'python --version 2>&1'

might be the short answer to your issue

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.