1

I run a simple python script by crontab in a CentOS 7.x server. This is the code:

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
#MAILTO=root
MAILTO=my_email_address

00 15 * * * root /usr/bin/python ./home/python_devs/run_program.py >> /home/logs/Python_log_`date +\%Y-\%m-\%d_\%H\%M`.log

Unfortunately, it creates the log file, but it is completely blank. If I remove the >> .... the script output is being sent to my email address defined in MAILTO= field. So, how to save that output into the log file, which I then send by email? Thank you.

R99Photography
  • 71
  • 1
  • 2
  • 10

1 Answers1

0

Try this line:

00 15 * * * /usr/bin/python /home/python_devs/run_program.py >> /home/logs/Python_log_`date +\%Y-\%m-\%d_\%H\%M`.log 2>&1

I'm unclear why you had 'root' at the start of the line. Maybe that is a Centos-ism (I've always used debian based systems). But I've removed it since it appears you are trying to run a user file anyway.

Normally (debian) if you want root to run something you put it on the sudo crontab. I also removed the . before the path to the file.

Finally the 2>&1 also redirects stderr into your log. Maybe there is an error happening early and thus nothing is getting written to log, this will catch this case (and is a good practice anyway if you are trying to log a file this way)

Lost
  • 998
  • 10
  • 17
  • It works now, thank a lot for your help. Just another question: the script takes several minutes to complete. The proposed code store the date/time when the task starts. Is there any chance to get the date/time at the end? Thank you. – R99Photography Feb 22 '18 at 21:09
  • I'm unclear, are you wanting Cron to provide the time to the log? It would probably be easier to just have your python script add a `print(time.time()) ` to the end and it'll get redirected with the rest of the script out put. Would that work or are you needing a different solution? – Lost Feb 22 '18 at 21:17
  • I am newbie so I might not understood you well or maybe I explain badly my intentions :) I want that the end time of script is gonna store in the file name. So, does the code `print(time.time())` you had suggested me that target? At the moment, the code I have in crontab creates an output file at the time the run starts, but it ends dozens of minutes thereafter. I hope to be clear and understandable. :) – R99Photography Feb 22 '18 at 21:47
  • Sorry for the delay, didn't see the follow up. In the python script, if you `import time` then at the end of the file put `print(time.time())` then the last line that comes out of the program will be the completion time. Cron itself, so far as I know, only spawns the process and will have no way to know itself when the program finishes. So best if the program can generate this data itself – Lost Feb 26 '18 at 16:09