简体   繁体   中英

Executing a Python program from crontab

I have created a Python 2.7.3 program on my Raspberry Pi that writes an XML file. When I run this program using IDLE's F5 key, it runs and outputs the XML file. When I run the same program using an LXDE terminal at the pi@raspberry-pi ~ $ prompt by typing python program_name.py , it also works as intended and outputs the XML file.

Now I want to refresh the XML file every 15 minutes, and it sounds like I should be able to do this using crontab.

So I started with the command crontab -e which opens up the editor ( nano , in my case). I entered as the last line the following:

*/15**** python /home/pi/program_name.py

I also tried various variants as follows:

*/15**** sudo python /home/pi/program_name.py

and:

*/15**** python program_name.py

When I exit the program I get the error message:

"/tmp/crontab.nyQZsu/crontab":23: bad command
errors in crontab file, can't install.

Any ideas on what I am doing wrong?

The hour, minute, month, and other fields in a crontab file are whitespace-separated. Unless you've got a cron variant I haven't seen before, cramming all your fields together into a single blob like "****" is a syntax error.

From the POSIX Programmer's Manual:

[...] a crontab entry is a text file consisting of lines of six fields each. The fields shall be separated by <blank>s.

That's what the "bad command errors in crontab file" message is telling you: The file you fed crontab is invalid, so the program refuses to "install" (accept) it.

For comparison, here's the error I got when trying to install a file that included a deliberately bogus line, ***** /bin/echo :

$ crontab -e
crontab: installing new crontab
"/tmp/crontab.XXXXe2lUUa":5: bad hour
errors in crontab file, can't install.
Do you want to retry the same edit? n
crontab: edits left in /tmp/crontab.XXXXe2lUUa
$

Try to use 15 instead of /15

Also, if you want a crontab entry to run as root, it's better to put it in a /etc/cron.d/ file than in root's own user-level crontab.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM