To run a Python script you can type 'python script.py'. But did you know it is also possible to run a script without typing 'python' in front of the file name?

Executing a Python script from the terminal without typing python in front of the file name.

This article contains the strangest word I ever heard in programming land: Shebang. A Shebang is a character sequence containing the two characters #! and is used on Unix-like operating systems. When a text file starts with #!, it is considered a script and the program loader parses the rest of that line to check what interpreter should be used to execute the script.

Here is an example:

#!/bin/sh
echo Ommadawn

The first line has the shebang, followed by the path to the interpreter, in this case the system shell. In other words, every line in this script after the first line will be executed with the system shell.

./ommadawn
zsh: permission denied: ./ommadawn
chmod +x ./ommadawn
./ommadawn
Ommadawn

Make a Python script executable

You can use the same strategy to make Python files executable without having to type python in front of the file. Do make a Python script executable, save the following script as test.py:

#!/usr/bin/env python3
print("Ommadawn")

The path to the python interpreter depends on your system. Linux and macos both have Python 2 installed. If you installed Python 3 manually, things can get quite confusing. #!/usr/bin/env python3 works on macos.

chmod +x ./test.py
./test.py
Ommadawn

Warning

Making scripts executable, is a security risk. If the code in an executable script is changed by accident or with bad intentions, disasters can happen on your machine. Think carefully before making a script executable!

Written by Loek van den Ouweland on 2020-08-21.
Questions regarding this artice? You can send them to the address below.