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
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.
my_app.sh.PYTHON_MINIMUM_MAJOR and PYTHON_MINIMUM_MINORcheck_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+')";