Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Practical Python Programming for IoT

You're reading from   Practical Python Programming for IoT Build advanced IoT projects using a Raspberry Pi 4, MQTT, RESTful APIs, WebSockets, and Python 3

Arrow left icon
Product type Paperback
Published in Nov 2020
Publisher Packt
ISBN-13 9781838982461
Length 516 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Gary Smart Gary Smart
Author Profile Icon Gary Smart
Gary Smart
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

Preface 1. Section 1: Programming with Python and the Raspberry Pi
2. Setting Up your Development Environment FREE CHAPTER 3. Getting Started with Python and IoT 4. Networking with RESTful APIs and Web Sockets Using Flask 5. Networking with MQTT, Python, and the Mosquitto MQTT Broker 6. Section 2: Practical Electronics for Interacting with the Physical World
7. Connecting Your Raspberry Pi to the Physical World 8. Electronics 101 for the Software Engineer 9. Section 3: IoT Playground - Practical Examples to Interact with the Physical World
10. Turning Things On and Off 11. Lights, Indicators, and Displaying Information 12. Measuring Temperature, Humidity, and Light Levels 13. Movement with Servos, Motors, and Steppers 14. Measuring Distance and Detecting Movement 15. Advanced IoT Programming Concepts - Threads, AsyncIO, and Event Loops 16. IoT Visualization and Automation Platforms 17. Tying It All Together - An IoT Christmas Tree 18. Assessments 19. Other Books You May Enjoy

Running a Python script at boot

There will come a time when you have developed an awesome IoT project and you want it to run automatically every time you start your Raspberry Pi. Here is one simple way to achieve this using a feature of cron, the Unix scheduler. If you are not familiar with the basics of cron, search the web for cron tutorial—you'll find heaps of them. I've provided curated links in the Further reading section.

Here are the steps to configure cron and make a script run on boot:

  1. In your project folder, create a bash script. I've named it run_on_boot.sh:
#!/bin/bash

# Absolute path to virtual environment python interpreter
PYTHON=/home/pi/pyiot/chapter01/venv/bin/python

# Absolute path to Python script
SCRIPT=/home/pi/pyiot/chapter01/gpio_pkg_check.py

# Absolute path to output log file
LOG=/home/pi/pyiot/chapter01/gpio_pkg_check.log

echo -e "\n####### STARTUP $(date) ######\n" >> $LOG
$PYTHON $SCRIPT >> $LOG 2>&1

This bash script will run a Python script using the absolute paths for both the script and its Python interpreter. Also, it captures any script output and stores it in a log file. For this example, we're simply going to run and log the output of gpio_pkg_check.py on boot. It's the last line that ties everything together and runs and logs our Python script. The 2>&1 part at the end is necessary to ensure that errors, in addition to standard output, are also logged.

  1. Mark the run_on_boot.sh file as an executable file:
$ chmod u+x run_on_boot.sh

If you are not familiar with the chmod command (chmod means change mode), what we are doing is giving the operating system permission to execute the run_on_boot.sh file. The u+x parameters mean for the current User, make the file eXecutable. To learn more about chmod, you can type chmod --help or man chmod in the Terminal.

  1. Edit your crontab file, which is the file where cron scheduling rules are stored:
$ crontab -e
  1. Add the following entry to your crontab file, using the absolute path to the run_on_boot.sh bash script we created in step 1:
@reboot /home/pi/pyiot/chapter01/run_on_boot.sh &

Do not forget the & character at the end of the line. This makes sure the script runs in the background.

  1. Run the run_on_boot.sh file manually in a Terminal to make sure it works. The gpio_pkg_check.log file should be created and contains the output of the Python script:
$ ./run_on_boot.sh
$ cat gpio_pkg_check.log
####### STARTUP Fri 13 Sep 2019 03:59:58 PM AEST ######
GPIOZero Available
PiGPIO Available
  1. Reboot your Raspberry Pi:
$ sudo reboot
  1. Once your Raspberry Pi has finished restarting, the gpio_pkg_check.log file should now contain additional lines, indicating that the script did indeed run at boot:
$ cd ~/pyiot/chapter01
$ cat gpio_pkg_check.log

####### STARTUP Fri 13 Sep 2019 03:59:58 PM AEST ######

GPIOZero Available
PiGPIO Available

####### STARTUP Fri 13 Sep 2019 04:06:12 PM AEST ######

GPIOZero Available
PiGPIO Available

If you are not seeing the additional output in the gpio_pkg_check.log file after a reboot, double-check that the absolute path you entered in crontab is correct and that it works manually as per step 5. Also, review the system log file,  /var/log/syslog, and search for the text, run_on_boot.sh.

Our cron-based example of running a script on boot is one of many options that are available in Unix-based operating systems such as Raspbian. Another common and more advanced option using systemd can be found on the Raspberry Pi website at https://www.raspberrypi.org/documentation/linux/usage/systemd.md. Irrespective of the option you prefer, the key point to remember is to ensure your Python scripts run from within their virtual environment.

We have now learned alternative methods to run a Python script, which will help you in the future to correctly run your Python-based IoT projects after they are developed or start them when your Raspberry Pi boots if required.

Next, we will now move on to making sure your Raspberry Pi is set up and configured correctly for the GPIO and electronic interfacing that we'll be diving into in the next chapter, Chapter 2, Getting Started with Python and IoT, and subsequent chapters.

You have been reading a chapter from
Practical Python Programming for IoT
Published in: Nov 2020
Publisher: Packt
ISBN-13: 9781838982461
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime