Cron – Capture errors in python cronjobs

cronpython

I have a python script as a cron job that is called like this

/path/to/python /path/to/myscript myparam

When an error occurs in the script, the cronjob silently fails. When I run the same command from the command line, I get a stack trace. How can I bring my script to output the stack trace (or write it to a file) when running as a cron job? I have already set the MAILTO variable. I have also tried putting

/path/to/python /path/to/myscript myparam 2>&1 >> /path/to/logfile

in the crontab but logfile remains empty.

Update: The call without output redirection works now. It was not an issue with the python script, but a wrong separator in the MAILTO crontab setting. Remember: Use commas and don't put spaces after the commas!

Best Answer

You used the wrong order.

  • 2>&1 means that redirect standard error to the standard output and both to the terminal
  • >> /path/to/logfile redirects standard output to the log file. You didn't mentioned the standard error, so it still go to the terminal.

Try this:

/path/to/python /path/to/myscript myparam >> /path/to/logfile 2>&1

Make sure that the user who run this script has write permission to the log file.