I've been all over the internet looking for a solution for this but everybody seems to have different answers and none of them work. I have a python script that emits audio through the headphone jack when ran, and I want it to run on boot without having to connect to a monitor and run it myself. How would I make /home/pi/Desktop/sample.py run on boot?
You should use a systemd service. These services are used to start programs. You will find many examples how to do it at tag systemd-startup.
Have you tried
Assuming you can run the script from the terminal, as user
pi (i.e. No
sudo required), and it runs correctly:
From the terminal (CLI; don't enter the
$ in column 1 - it's the shell prompt):
$ crontab -e
You may be prompted to choose an editor for your
picoare reasonable choices if you're not familiar with the other editors.
In the editor, add this one line:
@reboot /bin/sleep 10; /usr/bin/python /home/pi/Desktop/sample.py >> sample_py_log.txt 2>&1
Let's break it down:
@reboot- runs the designated program(s) when
crondaemon is started
/bin/sleep 10- wait/
sleepfor 10 seconds before resuming this command; this allows time for any other resources in your script to be started (e.g. sound drivers, etc)
shthere's another command coming
/usr/bin/python- you may need
/usr/bin/python3instead - depending upon how your system is configured
/home/pi/Desktop/sample.py- full path to your script
>> sample_py_log.txt- re-directs output (
stdout) of script to the named file
stdoutso that you "capture" any error messages thrown by your script. This is necessary because
cronwas not designed to be "interactive" w/ users.
Finally, save your edited
crontab, exit the editor, and reboot your RPi to test. Let us know if you have questions.