Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect python version in shell script

Tags:

python

shell

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"?

like image 762
TheRealNeo Avatar asked May 26 '11 16:05

TheRealNeo


People also ask

How do I check my Python version in shell script?

To check your Python version, run python – version in your command line (Windows), shell (Mac), or terminal (Linux/Ubuntu). To check your Python version in your script, run import sys to get the module and use sys. version to find detailed version information in your code.

How do I find Python version in Linux?

The easiest way to check Python version in Linux is using python -V command. All we need is to open the terminal then type python -V in the prompt. The Python version will be listed.

What is the current Python version?

Python 3.9. 6, documentation released on 28 June 2021.


1 Answers

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.

like image 190
NPE Avatar answered Sep 21 '22 10:09

NPE