Executing a Python script from the terminal without typing python in front of the file name.
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?
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.
- Save this script as
ommadawn(no extension needed)
- Execute the script and notice the error:
./ommadawn zsh: permission denied: ./ommadawn
- Fix this by making the file executable
chmod +x ./ommadawn
- Execute the script and notice the result:
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
#!/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.
- Make the file executable
chmod +x ./test.py
- Execute the script:
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!