Home > Software design >  Python "print" function not working with crontab
Python "print" function not working with crontab

Time:05-19

I was trying to run some python script periodically in a linux-based OS, and after some quick research, I found that crontab is a classic approach for this. I was a newbie to that command, so I made sure to keep in mind the common existing recommendations for it, and (cautiously) I decided to firstly go with a very simple python code, myscript.py:

#!/usr/bin/python3

print("If you see this, your periodic code ran OK!")

The 'cron table' (crontab -l) file looked as follow, which was suppossed to run myscript.py every minute (I wanted to quick-test it):

* * * * * /usr/bin/python3 /home/my_user_folder/Desktop/test/myscript.py

The seconds passed, the script reached its first elapsed minute... and nothing happened. To "solve it", I tried several things, but eerily (to me) I realized that most (if not all) tutorials and posts, used to store messages in .txt or similar files. I did something alike (after some hours, trials and no success), by modifying myscript.py to:

#!/usr/bin/python3

# NOTES:
# 1. This code is the 'final version' after several trials
# 2. Remember that I was aiming to automate anything, just
#    to get familiar with `crontab`; in this case, storing
#    the current time to some .txt file was enough.

import time

t = time.localtime()
current_time = time.strftime("%H:%M:%S", t)

with open('/home/my_user_folder/Desktop/test/readme.txt', 'a') as f:
    f.write(current_time)
    f.write('\n')

...and it worked. I felt a bit silly, because I got to realize that my initial implementation (in regards of code, environmental settings, permissions, etc.) was indeed correct from the beginning, and yet using the Python command print to 'test' recurrent tasks with crontab 'did not work'...

Why?

CodePudding user response:

The standard output of a command executed from crontab is not sent to the standard output of your shell. (It wouldn't make much sense for it to do so; a cron job will continue to run after you've logged out.)

Typically crontab will (attempt to)email the output to you. This is configurable.man 5 crontab` for more information.

Rather than modifying your Python script to redirect its own output, you can redirect the output in the crontab entry itself:

* * * * * /usr/bin/python3 /home/my_user_folder/Desktop/test/myscript.py > output.txt
  • Related