Easy

Raspberry Pi Zero: Deploy Your Project

Learn how to make your Python project load when the Pi Zero boots

26 November 2015 · Tutorial · about 15 minutes

Once you've carefully crafted your Python script, you're going to want to set it to run at startup so your code can be run on a headless, networkless Pi Zero. This guide will walk you through one of many ways to get your Python running when your Pi boots.

Preparing your Project

For the sake of this tutorial, I'm going to assume your project lives in the directory /home/pi/my_project and that the main script is called my_script.py, when you see this directory and script name in the code below you can substitute your own.

Make sure your script lives in a tidy subdirectory of /home/pi, you might even have a directory of projects or your own filing system, it doesn't matter too much.

Also, make sure your Python script is up to snuff. Test it thoroughly and make sure it's ready to be deployed. Once it's up and running on a Pi Zero, or built into your project, it's not always going to be easy to debug.

Preparing a Startup Script

First we're going to need to delve into a little bit of Bash. Bash is the language of the Raspberry Pi terminal, but don't worry we'll only use a little bit to ensure our Python script is run, and stays running.

Fire up Terminal, you can find it in the Raspberry Pi menu under Accessories.

Now use nano to a new file in your home directory, let's call it run.sh:

nano run.sh

In the newly opened nano session, type the following:

# !/usr/bin/env bash
cd /home/pi/my_project/
while [ 1 ]; do python my_script.py; sleep 1; done

This uses a simple while loop which runs your Python script every time it exits. That means if it crashes or quits for some reason, it'll automatically get loaded again. The sleep 1 ensures this doesn't happen at a ridiculous rate if your script crashes on load.

Now we'll make this script executable:

chmod +x /home/pi/my_script.py

Running Your Startup Script

The final piece of the puzzle is to instruct your Pi to run the new startup script... when it starts up.

I tend to do this using the file /etc/rc.local because it doesn't require you log in or boot to desktop in order to function.

Open up the rc.local file with nano, like so:

sudo nano /etc/rc.local

And just before the line exit 0 add a call to your script:

/home/pi/run.sh > /dev/null 2>&1

The cryptic 2>&1 on the end of this command is ugly Bash syntax for redirecting both error and standard outputs, this means your logged in sessions won't get periodically spammed with garbage from your running script. It's tucked away neatly in the background, and all the output is discarded into the void that is /dev/null.

Reboot

All that's left is to reboot. If you're brave you can unplug your screen and keyboard and wait for your Pi to spring to life.