The Raspberry Pi is a tiny, affordable computer that is loved by hobbyists, educators, and developers. Its small size, low cost, and ability to run Linux make it the perfect platform for learning programming and building electronics projects.

One of the most popular things to do with a Raspberry Pi is to write Python scripts. Python comes pre-installed on Raspbian, the official operating system for Raspberry Pi. This makes it very easy to get started with Python programming.

In this comprehensive guide, you‘ll learn several methods for running Python scripts on your Raspberry Pi:

  1. Running Python code directly in the terminal
  2. Creating and executing Python script files
  3. Setting up your Raspberry Pi to automatically run a Python script on boot

I‘ll also provide some sample Python scripts you can test out. Let‘s get started!

Prerequisites

Before you can run Python scripts on your Raspberry Pi, make sure you have the latest version of Raspbian installed with Python 3:

pi@raspberrypi:~ $ python3 --version
Python 3.7.3

If Python 3 isn‘t installed for some reason, update your package list and install it:

sudo apt update
sudo apt install python3

It‘s also recommended to update all your packages to the latest versions:

sudo apt update 
sudo apt upgrade

Let‘s move on to running some Python!

Method 1: Running Python in the Terminal

The quickest way to get started with Python on your Pi is to simply open up a terminal and start typing Python code.

To open a terminal, go to Menu > Accessories > Terminal or press Ctrl+Alt+T.

You‘ll see a terminal window open with a prompt like this:

pi@raspberrypi:~ $

To enter the Python interpreter, type python3 and hit Enter:

pi@raspberrypi:~ $ python3
Python 3.7.3 (default, Dec 20 2019, 18:57:59)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.  
>>>

Now you are in a Python 3 interpreter shell, indicated by the >>> prompts. Here you can type any valid Python code and execute it immediately by hitting Enter.

For example, let‘s try out a simple print statement:

>>> print("Hello Raspberry Pi!")
Hello Raspberry Pi!

We can also do math:

>>> 2 + 2
4

And make use of variables:

>>> name = "Ada"
>>> print("Hello there, " + name)
Hello there, Ada

This is useful for testing out small Python scripts and experimenting with syntax. But ideally you‘ll want to save your code to a file you can run as a program. So let‘s look at that next.

To exit the Python interpreter and return to the terminal, type exit() and hit Enter.

Method 2: Creating and Running Python Scripts

Writing Python code in a terminal is fine, but it can get tedious to type and rewrite code. It‘s better to save your scripts as .py files that can be edited with a text editor and executed like standard programs.

Follow these steps to create and run a Python script on your Pi:

  1. Open your text editor and create a new file called my_script.py (or any name you want)

  2. Add the following code and save the file:

print("Executing my Python script!")

x = 5
y = 10
z = x + y
print(z)
  1. Open a terminal window and cd to the location where you saved your script

  2. Make the script executable with the command:

 chmod +x my_script.py
  1. Execute your script:
./my_script.py

You should now see the output from your Python script printed in the terminal!

Executing my Python script! 
15

From now on you can run that Python script just like any other program on your Raspberry Pi.

Feel free to edit the code and add functions to create more robust scripts. Here are some ideas:

  • Import modules to extend functionality
  • Take command line arguments and input
  • Process and analyze data
  • Automate tasks
  • Make projects with LEDs, motors, sensors, etc

Running scripts from dedicated .py files helps organize your code and allows for much more sophisticated programs than typing directly into the Python interpreter.

Method 3: Autorunning Python Scripts on Boot

Perhaps you want your Python program to automatically start running as soon as you boot up your Raspberry Pi, without needing to manually launch it. This is easy to achieve as well.

Raspbian uses systemd to control services that launch on startup. We simply need to create a systemd service file that executes our Python script.

Follow these steps:

  1. Create and test your Python script as shown in the previous section

  2. Create a service file with sudo privileges using nano or your preferred editor:

sudo nano /etc/systemd/system/myscript.service 
  1. Add the following, replacing /home/pi/my_script.py with your script‘s location:
[Unit]
Description=My Python Script
After=multi-user.target

[Service]  
Type=simple
ExecStart=/usr/bin/python3 /home/pi/my_script.py
Restart=on-failure

[Install]
WantedBy=multi-user.target
  1. Save and exit the file

  2. Reload systemd to pick up your new service:

sudo systemctl daemon-reload
  1. Enable your script to launch on boot:
sudo systemctl enable myscript.service

Now your Python program will automatically start running every time you boot up your Raspberry Pi!

To check that it is working, reboot your Pi with sudo reboot and check your script‘s output, or monitor it with systemctl status myscript.service.

This is just one way to auto-run Python scripts. Other options include adding it to rc.local, crontab, or making a desktop file. But systemd is versatile and easy for running background processes.

Conclusion

I hope this guide has helped demystify several methods for executing Python code on your Raspberry Pi. Here‘s a quick recap of what you‘ve learned:

  • Use the python3 command to access the interactive interpreter
  • Create dedicated .py scripts with entire programs
  • Make scripts executable and invoke them in the terminal
  • Automatically run Python code on boot with systemd

With these skills you are fully prepared to write and run all types of Python programs on your Pi. The possibilities are endless!

Some other things you may wish to explore next are:

  • Using cron jobs to schedule script execution
  • Building Python GUIs
  • Accessing the Pi‘s GPIO pins
  • Creating a web server with Flask
  • Building a Python-based security camera or IoT device

No matter your skill level or project goal, Python on Raspberry Pi is fun, productive, and powerful. Have fun bringing your ideas to life!

Similar Posts