Search code examples
pythonlinuxubuntucron

Cannot run python script in a crontab


I am trying to run a python script and I am using this code to run the crontab:

SHELL = /home/boogieman/codeCopy.py
PATH = /sbin:/bin:/usr/sbin:/usr/bin
MAILTO = ""
* * * * * /usr/bin/python/ /home/boogieman/codeCopy.py

I tried SHELL = /bin/bash too but still cannot see any difference. When I run the codeCopy.py in my terminal, it works like a charm. But still cannot figure out what am I doing wrong with the crontab. Here is a piece of my code which saves a dictionary into a csv file:

from time import strftime
t = strftime('%a, %d %b %Y %H:%M:%S')

body.update({'Time':t})

with open('/home/boogieman/r3edata.csv','a+', newline='') as fhandle:
        writer = csv.writer(fhandle)
        items = body.items()
#       writer.writerow([key for key, value in items])
        writer.writerow([value for key, value in items])

I am trying to save a copy of the dictionary every time when it runs. The solutions I found on several pages didn't work for me. I changed Shell path, updated exact file paths and tried the script accessible for every user. I explicitly used /usr/bin/python/ in my crontab command and tried #!/usr/bin/python/ in my python script too. Both of them didn't work.

Can you please help me fix this? thank you in advance


Solution

  • Try the following line in /etc/crontab:

    * * * * * python3 /home/boogieman/codeCopy.py
    

    you can also consider this line:

    * * * * * cd /home/boogieman && python3 codeCopy.py
    

    so you'll be running your script in the correct folder.