Python script from Cron
Question: I have finished a program in Python and I intend for it to be run from my RPi
every _n_ hours. This will be my first time running such program/script in
this way and I would like to know if there is anything I should know/have
written into the script before I add it to my crontab?

I'm also not sure how such an entry in the crontab would look. Do I write
something like:

    
    
    * 2 * * * pi `python /home/pi/Desktop/myProg.py`
    

With back-ticks around the command or would I launch myProg.py from within a
shell script that I would call from the crontab?

    
    
    * 2 * * * pi /home/pi/Desktop/launchMyProg.sh
    

Also, I had some `print` statements in the program that I commented out as
they were mainly for debug during writing it, but on second thoughts it would
be useful for me to have these for debug info but directed to the
`/var/log/messages` or other log file which I can monitor with `tail -f
/var/log/messages` command.

How would I do that exactly? Thanks.


Answer: You are on the right track. To fire a python script every _n_ hours, do this:

    
    
    * */n * * * python /home/pi/Desktop/myProg.py
    

That's it. Make sure that you are editing the sudo level crontab, which is
accessed via `sudo crontab -e`.

Your code would actually have the script run at 2 am every day - it
technically says "run whenever the hour is equal to `2`". `* */n * * *` says
"run whenever the hour is divisible by `n`". A GREAT resource on crontab can
be found here: [Schedule tasks on Linux using
crontab](http://kvz.io/blog/2007/07/29/schedule-tasks-on-linux-using-crontab/)

Logging the output is also easy. If you had a log file on your desktop called
myLog.log, you would add `>> /home/pi/Desktop/myLog.log` to end of the crontab
entry. That would make the entry look like this:

    
    
    * */2 * * * python /home/pi/Desktop/myProg.py >> /home/pi/Desktop/myLog.log
    

**EDIT** (thanks to @Iamreck): Another option for outputting to a file is with
sys.stdout. This would accomplish the same goal. To do it this way, add the
following to your Python script:

    
    
    import sys
    sys.stdout = open("myLog.log","w")    
    sys.stderr = open("myLogErr.log","w")   
    print "stdout test"
    

You would also have to change the working directory to your Desktop when doing
this, and this can be done with the top answer at [this SO
post](http://stackoverflow.com/questions/1432924/python-change-the-scripts-
working-directory-to-the-scripts-own-directory)

