How to Always run Python 3 from Bash

Given a directory that contains:

| |- app.py |- requirements.txt |- ... |- <- other-files -> |- ...
Code language: HTML, XML (xml)

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
Code language: Bash (bash)

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)
Code language: Bash (bash)

Or by calling the version argument:

python -V # Python 3.7.6
Code language: Bash (bash)

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

Subscribe
Notify of
guest
1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
trackback

[…] Given a directory that contains: 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: Now instead of running python app.py or python3 app.py, you can … Read more […]