Jack Barber / Website Design

Automatically Run a Python Script at Boot in Raspbian

Automatically Run a Python Script at Boot in Raspbian

I've recently been building a desktop arcade machine with Cameron, my work experience student. We were exploring how to get stuff to happen once the Raspberry Pi we are using for the system had booted.

Firstly, we wanted Chrome to open automatically in 'kiosk' mode. This is where the browser loads a pre-selected web page but does not show any of the normal browser interface (address bar, status bar).

Secondly we had an idea to get the monitor to only power on once Chrome had loaded and the game was ready to play - in an attempt to hide the desktop environment from the user's view entirely.

Here's how we did each:

Loading Chrome Automatically in Raspbian at Boot

You'll need to attach your Pi to the network, boot it up and then SSH into it, like this:

Once you've got access, type this into your terminal:

sudo nano ~/.config/lxsession/LXDE-pi/autostart

For the purposes of this tutorial I'm presuming you have a single user account called 'pi' - hence LXDE-pi in the command above. If you have a different username you may need to adjust the command accordingly.

You will then be presented with this - although the exact lines on your file may be different:

Simply enter this new line at the bottom of the file:

@chromium-browser —kiosk http://example.com

There are lots of 'flags' you can utilise when running Chrome - here's a comprehensive list. For this example I've only shown -kiosk.

Save autostart by pressing ctrl+X, then hit Y to confirm your changes.

To test whether it works or not you'll need to reboot (or at least log out and back in again) to your Pi. Once Chrome opens in kiosk mode, the easiest way to close it is to use ctrl+W - you'll then be back to the desktop environment.

Running a Python Script Automatically in Raspbian at Boot

Again, connect to your Pi and create your Python file, perhaps something like this:

sudo nano MONITOR.py

Once the file opens in nano, enter your code, perhaps something like this:

Save your python script by pressing ctrl+X, then hit Y to confirm your changes.

Now we need to run this script at boot - which is exactly the same process as for Chrome, above.

Enter this into your terminal:

sudo nano ~/.config/lxsession/LXDE-pi/autostart

At the end of the file add this line:

@sudo python MONITOR.py

Save autostart by pressing ctrl+X, then hit Y to confirm your changes.

We're running the script as root (sudo) because it uses GPIO pins.

To test whether it works or not you'll need to reboot (or at least log out and back in again) to your Pi. There's a little more to get right here to work out whether your script is running or not - namely sound electronics. Provided you've checked your breadboard everything should be OK.

Happy tinkering!