You want to arrange for a script or program to start automatically every time the Raspberry Pi reboots.
Debian Linux, upon which most Raspberry Pi distributions are based, uses a dependency-based mechanism for automating the running of commands at startup. This is a little tricky to use and involves creating a configuration file for the script or program that you want to run in a folder called init.d.
Discussion
The following example shows you how to run a Python script in your home directory. The script could do anything, but in this case, the script runs a simple Python web server, which is described further in Recipe 7.16.
The steps involved in this are:
1. Create an init script.
2. Make the init script executable.
3. Tell the system about the new init script.
First, create the init script. This needs to be created in the folder /etc/init.d/. The script can be called anything, but in this example, we will call it my_server.
Create the new file using nano with the following command:
$ sudo nano /etc/init.d/my_server |
Paste the following code into the editor window and save the file:
### BEGIN INIT INFO # Provides: my_server # Required-Start: $remote_fs $syslog $network # Required-Stop: $remote_fs $syslog $network # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Simple Web Server # Description: Simple Web Server ### END INIT INFO #! /bin/sh # /etc/init.d/my_server |
This is quite a lot of work to automate the running of a script, but most of it is boilerplate code. To run a different script, just work your way through the script, changing the descriptions and the name of the Python file you want to run.
The next step is to make this file executable for the owner, which you do using this command:
$ sudo chmod +x /etc/init.d/my_server |
Now that the program is set up as a service, you can test that everything is OK, before you set it to autostart as part of the boot sequence, using the following command:
$ /etc/init.d/my_server start Starting My Server Bottle v0.11.4 server starting up (using WSGIRefServer())… Listening on http://192.168.1.16:80/ Hit Ctrl-C to quit. |
Finally, if that runs OK, use the following command to make the system aware of the new service that you have defined:
$ sudo update-rc.d my_server defaults |
See Also
For more information on changing file and folder permissions, see Recipe 3.13.