How to Always Run Python 3 From Bash


Given a directory that contains:

|
|- app.py
|- requirements.txt
|- ...
|- <- other-files ->
|- ...

We can create a runme.sh file to always make sure we are running python 3.

Create a shell script

Create a file called runme.sh and put the following code in:

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

if [[ $? == 0 ]]; then
    [ ! -d "venv" ] && virtualenv -p python venv
    . venv/bin/activate
    pip install -r requirements.txt
else
    [ ! -d "venv" ] && virtualenv -p python3 venv
    . venv/bin/activate
    pip3 install -r requirements.txt
fi

python app.py

Now instead of running python app.py or python3 app.py, you can simply run sh runme.sh.

Why is this useful?

This is very useful when distributing applications onto servers where the environment is not containerised.

Additional tips

You can also get the python version:

python -c 'import sys; print(sys.version_info[:])'

# (3, 7, 6, 'final', 0)

Or by calling the version argument:

python -V

# Python 3.7.6

For tips on how to containerise an application, take a look at The Docker Quickstart Guide for Developers .