I have written a small python script that plays a track after the press of a button (and ignores further button presses until the track has completed). The script works perfectly fine when started from terminal, but I simply cannot find a way to make it start on reboot with cron.
Here is the script
import pygame pygame.init() pygame.mixer.init() music = pygame.mixer.music.load("/home/pi/Hoelderlin.mp3") from signal import pause from gpiozero import Button def on_press (): if pygame.mixer.music.get_busy() == False: pygame.mixer.music.play() button = Button(2) button.when_pressed = on_press pause()
The relevant line in crontab -e is:
@reboot /usr/bin/python3 /home/pi/hoelderlinbutton.py
Upon reboot, nothing happens after pressing the button. I've activated cron logging (Where do Cron error message go?) but the log indicates that the script was executed. I tried to log for any errors from the script by changing the line in crontab to this:
@reboot /usr/bin/python3 /home/pi/hoelderlinbutton.py > /home/pi/logs/backup.log 2>&1
But the created log file is empty.
I then experimented, based on various hints and ideas from previous posts and answers by:
- using either
sudo crontab -eor
- changing the working directory in crontab with
@reboot cd /home/pi && /usr/bin/python3 /home/pi/hoelderlinbutton.py;
- Executing the script in the background by appending
&at the end;
XDG_RUNTIME_DIR=/run/user/1000earlier in crontab -e or sudo crontab -e (see: https://wiki.archlinux.org/title/PulseAudio#Play_sound_from_a_non-interactive_shell_.28systemd_service.2C_cron.29
- Executing the script for user pi in sudo crontab -e, i.e.
@reboot sudo -u pi /usr/bin/python3 /home/pi/hoelderlinbutton.py(See No methods for running python script on startup are working)
But none of this got me anywhere. I'm a little out of my depth here, but I believe that some limitation in the crontab environment prevents the actual playing of the track (or perhaps causes an issue with the GPIO). Any ideas what else I can try?