Python is a fantastic language for programming the Pi, thanks to its ease of use and access to hardware, including GPIO. In this how-to article, we will look at how to run Python programs on the Pi.
It appears that, on Raspbian, a Python program that needs external libraries may not work using all the methods listed below. Installing additional libraries can be done using PIP, but these seem to only install libraries for programs running in the terminal window. This may be due to the fact that the Python IDE programs have their own local copy of Python. Therefore, it is recommended that you use the terminal window to run Python programs that require external libraries installed using PIP.
Python programs can be executed using a terminal window, but before we open the terminal, we need to know the full path to the Python program. For this example, my Python program is located in Documents > Python > Main.py.
Open a terminal window and use the “cd” command to change the working directory to the directory that contains your Python program. I used the following command:
To confirm that your Python program resides in this directory, you can use the command “dir”, and this will list all files and folders in that directory. If your Python program is not listed in the list of files, you will need to go back and find where your Python program resides.
At this point, we can now execute the Python program by using the “python” command. This command will execute the Python file that is stated after the command, as shown here:
Or, if your file contains spaces, it will be:
python “your file name.py”
Raspbian comes with a number of IDEs for programming, and one of these IDEs is the official Python IDE. To open this, click the Raspbian logo and then navigate to Programming > Python 3 (IDLE).
With the IDE loaded, click File > Open and then navigate to your Python program.
When the file opens, you can run the program by clicking Run > Run Module or by pressing F5 on the keyboard.
Thonny is another Python IDE that boasts a number of features, including a powerful debugger that can be used to step through code and watch variables. This IDE can also be used to run Python programs. First, click the Raspbian logo and then navigate to Programming > Thonny Python IDE.
In the IDE, click File > Open and then navigate to your Python program. With the program loaded, click Run > Run current script.
There are a number of ways to run Python programs on the Raspberry Pi. As stated before, some of these other methods may have issues with missing libraries, which is why it is recommended to run Python programs using the terminal window. Executing Python programs can also be done using SSH, and this method is identical to the terminal method.