How to Always run Python 3 from Bash

0 min read 186 words

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 .

Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags