Operation Manual

Making Python Programs Executable
Normally, the only way to run a Python program is to tell the Python software to open the file. With the shebang line at the top of the file, however, it’s
possible to execute the file directly without having to call Python first. This can be a useful way of making your own tools that can be executed at the
terminal: once copied into a location in the system’s $PATH environment variable, the Python program can be called simply by typing its name.
First, you need to tell Linux that the Python file should be marked as executablean attribute that means the file is a program. To protect the system from
malware being downloaded from the Internet this attribute isn’t automatically set, since only files that are marked as executable will run. To make the
helloworld.py file executable, use the chmod command (described in detail in Chapter 2, Linux System Administration) by typing the following:
chmod +x helloworld.py
Now try running the program directly by typing the following:
./helloworld.py
Despite the fact that you didn’t call the Python program, the helloworld.py program should run just the same as if youd typed python helloworld.py.
The program can only be run by calling it with its full location/home/pi/helloworld.pyor from the current directory by using ./ as the location. To
make the file accessible in the same way as any other terminal command, it needs to be copied to /usr/local/bin with the following command:
sudo cp helloworld.py /usr/local/bin/
The sudo prefix is required because, for security reasons, non-privileged users cannot write to the /usr/local/bin directory. With the helloworld.py file
located in /usr/local/bin, which is included in the $PATH variable, it can be executed from any directory by simply typing its name. Try changing to a
different directory, and then run the program by typing the following:
helloworld.py
To make your custom-made programs seem more like native utilities, you can rename them to remove the .py file extension. To change the helloworld.py
program in this way, just type the following line at the terminal as a single line:
sudo mv /usr/local/bin/helloworld.py
/usr/local/bin/helloworld
Once renamed, the program can be run simply by typing helloworld at the terminal or console.
Example 2: Comments, Inputs, Variables and Loops
Although the Hello World program is a useful, gentle introduction to a language, its not terribly exciting. By its nature, it covers