In this short post, I’ll explain what a Python shebang is and how to use it to properly run Python scripts. Also, I’ve included some examples you can use to configure your scripts for execution.
What is a shebang in Python?
Shebang is a special character sequence represented by
#! (hash and exclamation) characters followed by a path indicating what program should be used to execute a script. The shebang line, also called the interpreter directive, comes at the beginning of a script file. The hash sign ensures that the shebang line will be interpreted as a comment, having no influence on the execution of a script.
You can learn more about shebang lines in the UNIX-like operating systems here.
The syntax of a shebang directive is as follows:
For example, to execute the script using the Python 3, define the shebang as follows:
Let’s break down the above shebang line:
#!is used to mark the shebang line.
/usr/bin/envcommand is used to launch the interpreter included in the $PATH declaration where all system executables reside.
python3is the additional argument that is passed to the executable located on a specified path. In this case, it denotes what interpreter should an environment use.
Similarly, to use the Python 2 version for the script execution, define the shebang line as follows:
How to run a Python script using shebang?
Using shebang line is especially useful when running a script directly:
$ chmod +x myscript.py $ ./myscript.py
Rather than running it by explicitly specifying the interpreter:
$ python3 myscript.py
In the above example, when the script is executed by typing
./myscript.sh in the shell, it will actually be run as:
/usr/bin/env python3 myscript.py
You see the point – when no interpreter is defined in the command line, the Python shebang line helps the operating system to find the one.
Should I use shebang line in Python?
Whether using the shebang for running scripts in Python is necessary or not, greatly depends on your way of executing scripts.
The shebang decides if you’ll be able to run the script as a standalone executable without typing the python command. So, if you want to invoke the script directly – use the shebang. But learn to define it in a correct way, having in mind that probably you’ll be sharing scripts with other programmers too. If you define the path specific to your environment only, you could make it unusable for other programmers.