0

I have different python versions installed (from source) on my server. Now I'd like to be able to get the version of a python executable from another python script (running another python version).

I know I can do it from the shell with path/to/python -V. But I'd like to do it from a script, like:

command = ' '.join([pythonpath, '-V'])
output = subprocess.check_output( command, shell=True )
print output

But in this case check_output does not work as expected: the output is shown in the terminal but does not go into the variable output.

4
  • What is pythonpath? Commented Mar 13, 2019 at 20:06
  • @Aran-Fey Since it is a variable, I belive it must be the path to one of his Python commands Commented Mar 13, 2019 at 20:09
  • yes exactly, it's the path to one of the python executables Commented Mar 13, 2019 at 20:10
  • In the meantime I found a workaround here: linuxconfig.org/check-python-version. So the command is /path/to/python /path/to/check_python_script.py. With this command check_output works as expected. Commented Mar 13, 2019 at 20:12

1 Answer 1

1

Code:

#!/usr/bin/python2
# -*- coding: utf-8 -*-

from subprocess import Popen, PIPE

if __name__ == '__main__':

    cmd = '/usr/local/bin/python2'
    param = '-V'

    process = Popen([cmd, param], stdout=PIPE, stderr=PIPE)
    process.wait()

    # be aware, the order should be out, err for shell tools, but python reply shows in err, out, i've no idea why

    err, out = process.communicate()

    print out

Output:

Python 2.7.15

You can see source code here.

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

1 Comment

It doesn't work for me, same problem as with my own initial script: the result of out = process.communicate()[0].splitlines() is printed but the variable out is an empty list. Maybe it works on Python 3, I'm working on 2.7.15.

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.