105

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

3
  • 4
    why is python --version ungraceful? Maybe /usr/bin/env python --version? May 26, 2011 at 16:08
  • 5
    what I meant with "ungraceful" is that the string format may change in the future, invalidating the string parsing.
    – TheRealNeo
    Aug 6, 2014 at 12:31
  • 1
    Python 2.4 returns an error for python --version. You need to use python -V.
    – jww
    Feb 4, 2018 at 0:32

18 Answers 18

89

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.

4
  • 8
    You can also store the results in a variable: export PYTHON_VERSION=`python -c 'import sys; version=sys.version_info[:3]; print("{0}.{1}.{2}".format(*version))'` using that solution. Much nicer than the regex stuff below.
    – DragonTux
    Feb 2, 2017 at 10:00
  • 7
    For anyone else that lands here because you want to assure a certain python version is installed: I'm using this together with an assert, so I can use it in a bash script like this: if ! python3 -c 'import sys; assert sys.version_info >= (3,6)' > /dev/null; then
    – Thomas
    Sep 22, 2020 at 14:24
  • 2
    and just in case you need a specific major.minor version... if ! python -c 'import sys; assert sys.version_info[:2] == (3,9)' > /dev/null; then
    – Laurent
    Jan 6, 2022 at 23:03
  • Needs some shell logic around it, because many systems don't have a python binary but have python3. Also @DragonTux comment should be in the answer, as it's not obvious how to join Python tuples in a shell.
    – copycat
    Jan 6 at 5:34
37
python -c 'import sys; print sys.version_info'

or, human-readable:

python -c 'import sys; print(".".join(map(str, sys.version_info[:3])))'
1
  • Neat but for python3 you need parenthesis around print
    – Bostone
    Nov 4, 2022 at 16:50
22

You can use this too:

pyv="$(python -V 2>&1)"
echo "$pyv"
19

I used Jahid's answer along with Extract version number from a string to make something written purely in shell. It also only returns a version number, and not the word "Python". If the string is empty, Python is not installed.

version=$(python -V 2>&1 | grep -Po '(?<=Python )(.+)')
if [[ -z "$version" ]]
then
    echo "No Python!" 
fi

And let's say you want to compare the version number to see if you're using an up to date version of Python, use the following to remove the periods in the version number. Then you can compare versions using integer operators like, "I want Python version greater than 2.7.0 and less than 3.0.0". Reference: ${var//Pattern/Replacement} in http://tldp.org/LDP/abs/html/parameter-substitution.html

parsedVersion=$(echo "${version//./}")
if [[ "$parsedVersion" -lt "300" && "$parsedVersion" -gt "270" ]]
then 
    echo "Valid version"
else
    echo "Invalid version"
fi
3
  • 3
    Nice, thanks for this, but the problem is that some versions of python returns 4 digits and other with 3 digits, e.g. Python 2.7.12, so comparing 2712 with 300 doesn't work :(
    – Lilás
    Dec 2, 2016 at 23:52
  • It becomes less simple to do so, but you could get the integer value 2712, stick '0.' behind it, then compare it with '0.300' using logic found in stackoverflow.com/questions/11237794/…
    – Sohrab T
    Dec 4, 2016 at 19:21
  • On my macOs Catalina, this produces: "No Python!", with grep crashing (it gives out grep usage instructions). What's wrong? Nov 14, 2021 at 11:56
19

Here is another solution using hash to verify if python is installed and sed to extract the first two major numbers of the version and compare if the minimum version is installed

if ! hash python; then
    echo "python is not installed"
    exit 1
fi

ver=$(python -V 2>&1 | sed 's/.* \([0-9]\).\([0-9]\).*/\1\2/')
if [ "$ver" -lt "27" ]; then
    echo "This script requires python 2.7 or greater"
    exit 1
fi
3
  • Can you explain how if ! hash python works? The man page says "The /usr/bin/hash utility affects the way the current shell environment remembers the locations of utilities found." So if it's kind of like a cache of previously run commands, then what if I've never run python before? Would the check still work?
    – Atav32
    May 16, 2021 at 20:39
  • hash increases the performance for the console to find a command, from the man page it shall add utility locations to its list of remembered locations. So if you had never run python before, it will work (since it will add the path of this binary to this remembered locations list)
    – Lilás
    Jun 9, 2021 at 14:19
  • Doesn't work with python 3.10, because it's three digits long and gets truncated to 31 here
    – nonbirithm
    Mar 17 at 19:48
15

You can use the platform module which is part of the standard Python library:

$ python -c 'import platform; print(platform.python_version())'
2.6.9

This module allows you to print only a part of the version string:

$ python -c 'import platform; major, minor, patch = platform.python_version_tuple(); print(major); print(minor); print(patch)'
2
6
9
1
  • Indeed, the plaftorm module seems to be made for that. However, this seems a bit inferior to using sys.version_info because the platform module only appeared in Python 2.3 whereas sys.version_info appeared in Python 2.0
    – TheRealNeo
    Oct 6, 2016 at 13:43
9

You can use this command in bash:

PYV=`python -c "import sys;t='{v[0]}.{v[1]}'.format(v=list(sys.version_info[:2]));sys.stdout.write(t)";`
echo $PYV
8

using sys.hexversion could be useful if you want to compare version in shell script

ret=`python -c 'import sys; print("%i" % (sys.hexversion<0x03000000))'`
if [ $ret -eq 0 ]; then
    echo "we require python version <3"
else 
    echo "python version is <3"
fi
0
6

Adding to the long list of possible solutions, here's a similar one to the accepted answer - except this has a simple version check built into it:

python -c 'import sys; exit(1) if sys.version_info.major < 3 and sys.version_info.minor < 5 else exit(0)'

this will return 0 if python is installed and at least versions 3.5, and return 1 if:

  • Python is not installed
  • Python IS installed, but its version less than version 3.5

To check the value, simply compare $? (assuming bash), as seen in other questions.

Beware that this does not allow checking different versions for Python2 - as the above one-liner will throw an exception in Py2. However, since Python2 is on its way out the door, this shouldn't be a problem.

1
  • the test is wrong, it should be sys.version_info.major < 3 or (sys.version_info.major == 3 and sys.version_info.minor < 5) Mar 26, 2021 at 15:11
5

Detection of python version 2+ or 3+ in a shell script:

# !/bin/bash
ver=$(python -c"import sys; print(sys.version_info.major)")
if [ $ver -eq 2 ]; then
    echo "python version 2"
elif [ $ver -eq 3 ]; then
    echo "python version 3"
else 
    echo "Unknown python version: $ver"
fi
3

To check if ANY Python is installed (considering it's on the PATH), it's as simple as:

if which python > /dev/null 2>&1;
then
    #Python is installed
else
    #Python is not installed
fi

The > /dev/null 2>&1 part is there just to suppress output.

To get the version numbers also:

if which python > /dev/null 2>&1;
then
    #Python is installed
    python_version=`python --version 2>&1 | awk '{print $2}'`
    echo "Python version $python_version is installed."

else
    #Python is not installed
    echo "No Python executable is found."
fi

Sample output with Python 3.5 installed: "Python version 3.5.0 is installed."

Note 1: The awk '{print $2}' part will not work correctly if Python is not installed, so either use inside the check as in the sample above, or use grep as suggested by Sohrab T. Though grep -P uses Perl regexp syntax and might have some portability problems.

Note 2: python --version or python -V might not work with Python versions prior to 2.5. In this case use python -c ... as suggested in other answers.

3

This just returns 2.7, 3.6 or 3.9

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

which is what you usually you need...

0
2

Yet another way to print Python version in a machine-readable way with major and minor version number only. For example, instead of "3.8.3" it will print "38", and instead of "2.7.18" it will print "27".

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

Works for both Python 2 and 3.

2

In case you need a bash script, that echoes "NoPython" if Python is not installed, and with the Python reference if it is installed, then you can use the following check_python.sh script.

  • To understand how to use it in your app, I've also added my_app.sh.
  • Check that it works by playing with PYTHON_MINIMUM_MAJOR and PYTHON_MINIMUM_MINOR

check_python.sh

#!/bin/bash

# Set minimum required versions
PYTHON_MINIMUM_MAJOR=3
PYTHON_MINIMUM_MINOR=6

# Get python references
PYTHON3_REF=$(which python3 | grep "/python3")
PYTHON_REF=$(which python | grep "/python")

error_msg(){
    echo "NoPython"
}

python_ref(){
    local my_ref=$1
    echo $($my_ref -c 'import platform; major, minor, patch = platform.python_version_tuple(); print(major); print(minor);')
}

# Print success_msg/error_msg according to the provided minimum required versions
check_version(){
    local major=$1
    local minor=$2
    local python_ref=$3
    [[ $major -ge $PYTHON_MINIMUM_MAJOR && $minor -ge $PYTHON_MINIMUM_MINOR ]] && echo $python_ref || error_msg
}

# Logic
if [[ ! -z $PYTHON3_REF ]]; then
    version=($(python_ref python3))
    check_version ${version[0]} ${version[1]} $PYTHON3_REF
elif [[ ! -z $PYTHON_REF ]]; then
    # Didn't find python3, let's try python
    version=($(python_ref python))
    check_version ${version[0]} ${version[1]} $PYTHON_REF
else
    # Python is not installed at all
    error_msg
fi

my_app.sh

#!/bin/bash
# Add this before your app's code
PYTHON_REF=$(source ./check_python.sh) # change path if necessary
if [[ "$PYTHON_REF" == "NoPython" ]]; then
    echo "Python3.6+ is not installed."
    exit
fi

# This is your app
# PYTHON_REF is python or python3
$PYTHON_REF -c "print('hello from python 3.6+')";
2
  • 1
    Exactly what I was looking for. Thank you! May 24, 2020 at 15:18
  • nice script, but there's an issue on windows with it. There are default "python" and "python3" files that open microsoft store for python, so the if [[ ! -z $PYTHON3_REF ]] won't produced desired results if python was installed via "python" keyword.
    – Ubeogesh
    Oct 28, 2022 at 8:53
2

The easiest way would be:

if ! python3 --version ; then
    echo "python3 is not installed"
    exit 1
fi

# In the form major.minor.micro e.g. '3.6.8'
# The second part excludes the 'Python ' prefix 
PYTHON_VERSION=`python3 --version | awk '{print $2}'`
1
  • often times python 3 is installed as plain "python" command (without the 3)
    – Ubeogesh
    Oct 28, 2022 at 8:48
1

If you need to check if version is at least 'some version', then I prefer solution which doesn't make assumptions about number of digits in version parts.

VERSION=$(python -V 2>&1 | cut -d\  -f 2) # python 2 prints version to stderr
VERSION=(${VERSION//./ }) # make an version parts array 
if [[ ${VERSION[0]} -lt 3 ]] || [[ ${VERSION[0]} -eq 3 && ${VERSION[1]} -lt 5 ]] ; then
    echo "Python 3.5+ needed!" 1>&2
    # fail ...
fi

This would work even with numbering like 2.12.32 or 3.12.0, etc. Inspired by this answer.

3
  • Any reason for -1?
    – Mi-La
    Feb 28, 2019 at 12:27
  • 1
    probably because you're missing a } on line 3. you should also present it as a function if you're going to return.
    – copycat
    Jan 6 at 5:49
  • thanks, hopefully fixed now .. still I think that for inspiration it was ok ;-)
    – Mi-La
    Jan 6 at 10:29
0

We first need to detect the latest available interpreter:

for i in python python{1..9}; do which $i >/dev/null && pybin=$i ;done

[[ -n $pybin ]] && echo "found $pybin" || echo "python not found"

Example output:

found python3

If we want to then do something with the version string:

v=$($pybin -V | cut -d' ' -f2)

Full string:

echo ${v}

3.8.10

Only major + minor version:

echo ${v%.*}

3.8

Only major version:

echo ${v%%.*}

3
0

The below code snippets are being used by me to check the required Python version before calling the Python script. It will exit if the Python version doesn't meet the requirement.

#!/usr/bin/bash

REQUIRED_PV=3.8
/usr/bin/env python3 -V 2>/dev/null | gawk -F'[ .]' -v req_pv="${REQUIRED_PV}" '{
    cur_pv_major=int($2)
    cur_pv_minor=int($3)
    split(req_pv, tmp, ".")
    req_pv_minor=int(tmp[2])
    if (cur_pv_major == 0 || cur_pv_minor < req_pv_minor) {
        printf "MY_SCRIPT requires Python %s or greater!\n", req_pv
        exit 1
    }
}' || exit 1

/usr/bin/env python3 MY_SCRIPT "$@"
  • The output of /usr/bin/env python3 -V is for example Python 3.6.8.
  • The gawk will split it with the delimiter (A blank space) and .(A dot) into Python, 3, 8, and 10.
  • The error message will be fired in the below cases:
    • If the major number (e.g. 3) is null, which means there's no python3 in $PATH.
    • If the minor number (e.g. 10) is lower than the required minor number.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.