Invoking Python with the Shebang in a Portable Way

Invoking Python with the Shebang in a Portable Way

Linux allows any text file to be converted into a runnable script using the “shebang” line which is a hash symbol followed by an exclamation mark, followed by the path to the interpreter that will run the file. This must be on the first line of the text file.

For example to convert a text file into a runnable Python file we simply do:

#!/usr/bin/python3

print(“hello world”)

Now the script can be invoked like any other Linux executable:

./my_python_script.py

Instead of needing to supply the name of the interpreter:

python3 my_python_script.py

However this relies on the Python interpreter being at the path /usr/bin/python3 and nowhere else on the system. However Python can be installed at any path and is not necessarily in /usr/bin. If we pass the script to someone who has Python installed elsewhere then it will fail. To solve this we can invoke Python in a more portable way as follows:

#!/usr/bin/env python3

print(“hello world”)

The way this works is the env command is a utility to invoke another command with a modified environment. However without any options it just uses the default environment. So with no options we ask env to run whatever python3 it can find on the user’s default path. The env command is a fundamental component of all Linux distros and will always be found at the path /usr/bin/env and nowhere else, and is therefore unlikely to fail.