Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
938 views
in Technique[技术] by (71.8m points)

cron - Crontab not starting python program

I created a python program, "test.py" and have saved it under /home/pi/. When I go to run it in the terminal using "python3 /home/pi/test.py" it runs properly and speaks "hello world". The code is shown below.

import os
import alsaaudio

m = alsaaudio.Mixer()
current_volume = m.getvolume()
m.setvolume(35)

os.system("espeak 'Hello World!'")

I want this program to start whenever my raspberry pi starts up. I tried to add this line in crontab but my raspberry pi doesn't execute the command. Does anyone know why my program won't execute?

@reboot python3 /home/pi/test.py

Here is an image of the syslog crontab


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

can you try adding the full path to python3:

@reboot /usr/bin/python3 /home/pi/test.py


Also, regarding wanting to run the code on when the device boots - you can run your code as a service.
To do so create a .service file under /etc/systemd/system (for example my-code.service)

Enter the following inside the file

[Unit]
Description=My python service
After=network.target

[Service]
ExecStart=/usr/bin/python3 -u test.py
WorkingDirectory=/home/pi

[Install]
WantedBy=multi-user.target

Finally enable the service (in order for it to run on boot)

sudo systemctl enable my-code

If you want to run it independently you can also run

sudo systemctl start my-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...