Detect python version in shell script

python -c 'import sys; print sys.version_info'

or, human-readable:

python -c 'import sys; print(".".join(map(str, sys.version_info[:3])))'

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.

Tags:

Python

Shell