Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crontab in Python creates cron job, but doesn't run script

Tags:

python

cron

Not sure what I'm doing wrong whether it's the code, the directory, or something else. Please help!

from crontab import CronTab

my_cron = CronTab(user='bgoldberg')
job = my_cron.new(command='python /Users/bgoldberg/PythonScripts/FunStuff/writeDate.py')
job.minute.every(1)
my_cron.write()

And here's the writeDate.py script:

import datetime

with open('dateInfo.txt','a') as outFile:
    outFile.write('\n' + str(datetime.datetime.now()))

The writeDate.py script just writes the current timestamp to a txt file and it works fine when run separately. When I run python scheduleCron.py, it runs without error but it seems that it's not running the writeDate.py script because no txt file is created. When I enter crontab -l it correctly shows the job that was created: ***** python /Users/bgoldberg/PythonScripts/FunStuff/writeDate.py

Not sure what I'm doing wrong...

like image 513
BenG Avatar asked May 24 '26 13:05

BenG


1 Answers

This is a cron "gotcha". Cron uses the command

python /Users/bgoldberg/PythonScripts/FunStuff/writeDate.py

which you expect to write to your current working directory, but cron will write to /var/log/syslog or some variation of this by default. It is trying to write to some place you don't have the permissions to (but it won't die), so you need to specifiy the absolute path of your output file.

changing your line in writeDate.py to write to an absolute path:

with open('/Users/bgoldberg/dateinfo.txt', 'a') as outFile:

will solve your problem.

like image 183
d_kennetz Avatar answered May 27 '26 02:05

d_kennetz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!