0

What would be the difference between the following two ways to run cron? Basically, I'm just trying to write to a file and seeing which one is preferred/correct:

2 * * * * python script.py >> /tmp/script.log

vs:

2 * * * * python script.py >> /tmp/script.log 2>&1

It seems they both write to a log but perhaps the first one 'flushes' more frequently?

Most output is done by normal print statements:

print('hello')

Which I think is the equivalent of writing to sys.stdout with an implicit \n after each print.

David542
  • 339

1 Answers1

5

The first redirection appends the standard output (only) of script.py to the log file.

If the script produces any messages on the standard error channel (in Pythonese: writes to sys.stderr), those messages will be processed as usual by cron, i.e. the cron daemon will collect them and after the job has ended, will attempt to send them as a local email message to the user that owns the cron job.

Normally such local emails will be processed by the local Mail Transfer Agent (MTA for short) and they'll land into the local email inbox file of the user, e.g. /var/mail/<username>. But if the system has no local MTA installed, this process might fail and the cron job error messages might be lost.

If the system has a properly configured MTA that can also send mail outside the local system, this email delivery could be redirected to any email address you want.


The second redirection appends both standard output and standard error outputs to the log file. If the cron job exits with a non-zero result code, the cron daemon might still attempt to send a local email to the owner of the job, just to report the result code to the job owner.

Which one is preferred/correct? It depends on what your script is doing and if you want a more immediate notification of script errors (by email) or not.

telcoM
  • 96,466