pythonshell

Detect python version in shell script


I'd like to detect if python is installed on a Linux system and if it is, which python version is installed.

How can I do it? Is there something more graceful than parsing the output of "python --version"?


Solution

  • You could use something along the following lines:

    $ python -c 'import sys; print(sys.version_info[:])'
    (2, 6, 5, 'final', 0)
    

    The tuple is documented here. You can expand the Python code above to format the version number in a manner that would suit your requirements, or indeed to perform checks on it.

    You'll need to check $? in your script to handle the case where python is not found.

    P.S. I am using the slightly odd syntax to ensure compatibility with both Python 2.x and 3.x.