Hardware Reference
In-Depth Information
Making Python Programs Executable
Normally, the only way to run a Python program is to tell the Python software to open the
ile. With the shebang line at the top of the ile, however, it's possible to execute the ile
directly without having to call Python irst. 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 ile should be marked as executable—an attribute
that means the ile is a program. To protect the system from malware being downloaded
from the Internet this attribute isn't automatically set, since only iles that are marked as exe-
cutable will run. To make the helloworld.py ile 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 you'd typed python helloworld.py . The program can only be run by
calling it with its full location— /home/pi/helloworld.py —or from the current directory by
using ./ as the location. To make the ile accessible in the same way as any other terminal com-
mand, it needs to be copied to /usr/local/bin with the following command:
sudo cp helloworld.py /usr/local/bin/
The sudo preix is required because, for security reasons, non-privileged users cannot write
to the /usr/local/bin directory. With the helloworld.py ile 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 ile 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.
 
Search WWH ::




Custom Search