As @Ingo has said in his answer, systemd
is indeed a valid and current method for starting a program at boot time. I also agree that /etc/rc.local
should be avoided - this is not so much a matter of opinion as documented fact (see, for example):
The man page for systemd-rc-local-generator
states, “Support for /etc/rc.local is provided for compatibility with specific System V systems only. However, it is strongly recommended to avoid making use of this script today, and instead provide proper unit files with appropriate dependencies for any scripts to run during the boot process.”
However, there is a valid and current method for doing what you want that you may find simpler, easier and equally effective as long as you follow a few simple rules. This method is called cron
, and here's how it can work in your case:
1. Open a crontab
file:
From the command line, enter crontab -e
, OR if you need your script to run with root
privileges, enter sudo crontab -e
. If you don't need elevated privileges, you should use the former.
In either case, after entering this command, your terminal will open the crontab
file in an editor (nano
is a good choice if prompted to select an editor).
2. Edit the crontab
file:
In your case, enter the following line at the bottom of the crontab
file:
@reboot ( /bin/sleep 10; /usr/bin/python3 /home/pi/Desktop/server2.py ) >> /home/piDesktop/cronjoblog.txt 2>&1
Let's break this down:
@reboot
instructs cron
to run the following commands at boot time
sleep 10
tells cron
to sleep/wait for 10 seconds before proceeding to the next command
/usr/bin/python3 /home/pi/Desktop/server2.py
says use python3
to run the script in server2.py
>> /home/piDesktop/cronjoblog.txt 2>&1
redirects >>
the stdout
and stderr
streams 2>&1
to a text file on your desktop
3. Save the crontab
file, exit the editor and reboot
to test:
If you're using nano
as your editor, controlo to save, acknowledge the proposed filename with return, and controlx to exit nano
and return to the command line. Let us know if you run into any issues.
Addendum: The simple rules for using cron
are based on two facts:
cron
does not inherit your environment variables
Consequently, preface commands with an absolute path
. A related symptom is that any output from a program that runs successfully from the command line is "lost". Lost error messages in particular are not helpful! Therefore: redirect all messages to a log file.
cron
does not know what resources are required to run your program
Network and file services may not be available when cron
is started. If not, cron
doesn't know what to do! Prefacing commands with sleep
allows the system to get these services started before cron
calls on them.
python3 /home/pi/Desktop/server2.py &
that & is super important to fork the process into the background. Also you don't needsudo
as rc.local runs as root. Also it does NOT run with the same environment as your regular pi shell (watch out for file names without full paths).