As I’ve mentioned numerous times on this site, I use Raspberry Pis and Python extensively in my home automation system. Since all of my Pis are installed in enclosures, inside the walls, under the house, in the attic, and basically all other inaccessible places in my house, I don’t have direct access to all of them which makes it a huge pain when they restart for whatever reason (mostly power outages with the Pis that aren’t connected to backup batteries). To ensure that my apps start back up when the Pis power back on, I have them set to run at startup and in this article I will show you how to do the same.
As a quick note, this article is only intended to demonstrate how to run Python scripts at startup for Arch Linux. There are similar ways of achieving the same for other Linux distros, but this one is only for Arch Linux.
To begin with, you will need a Python app that you want to run every time your Raspberry Pi restarts. For my purposes, I will be using a Python script that broadcasts the system vitals (diskspace, memory, & CPU usage) for my Raspberry Pis. I will explain this script in my next article. For now, just know that the script is called “pybroadcast.py”.
Once you have your script ready, you will begin by creating a new service. To do that, type:
Make sure you replace “pybroadcast” with the name you want to use for your service. This will open a blank page where you will need to enter the following:
Description = [Enter your description here]
After = network.target
ExecStart = /usr/bin/env python2 /path/to/your/script.py
Restart = on-abort
WantedBy = multi-user.target
When you are done, press Ctrl+X, hit the “Y” key, and press enter. This will save your service file.
To test that your service is working, run the following 2 commands. Again, make sure you replace “pybroadcast” with the name of your service file from above.
systemctl start pybroadcast
If your service had any issues, it should spit out some errors at this point. Otherwise, you can verify that your service is running successfully by running the following:
systemctl status pybroadcast
If everything looks good, you are now ready to tell your service to run your Python script at startup by running the following:
systemctl enable pybroadcast
That’s it. Your Python script is now ready to run every time your Raspberry Pi restarts. It’ll be up to you to verify that your Python script is doing what it’s supposed to.
PayPal will open in a new tab.