Raspberry Pi A User Manual page 195

Hide thumbs Also See for Raspberry Pi A:
Table of Contents

Advertisement

179
C H A P T E R 1 2
A N I N T R O D U C T I O N T O P Y T H O N
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 executable—an 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 exe-
cutable will run. To make the helloworld.py file executable, use the chmod command
(described in detail in Chapter 3, "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 file accessible in the same way
as any other terminal command, it needs to be copied to /usr/local/bin with the fol-
lowing 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.

Hide quick links:

Advertisement

Table of Contents
loading

Related Products for Raspberry Pi Raspberry Pi A

This manual is also suitable for:

Raspberry pi b

Table of Contents