简体   繁体   中英

Run Python script from Ubuntu cronjob

I am trying to run a simple python script on a VM running Ubuntu 18 hosted on my Synology. The python script simply prints date and time in a file so I can check if it ran or not. It looks like this:

from datetime import datetime
with open('file.txt','a') as file:
    file.write('Recorded at: %s\n' % datetime.now())

I made a cronjob that looks like this:

* * * * * /home/anaconda3/bin/python3.7 /home/Documents/crontest.py

I have tried many variations. For instance not writing 3.7 and just simply write 'python'. I tried the default python path /usr/bin/python3.7.

Furthermore I tried to ad the shebang #!/home/anaconda/bin/python3.7 to the script and leaving out the path in the cronjob.

It feels like I am missing something elementary here. I tried many options as posted on Stack and other forums, but none of the options seem to fix my problem.

Using relative links in python scripts is not allowed when running cronjobs. So it works when I write it like this:

from datetime import datetime
with open('/home/Documents/file.txt','a') as file:
    file.write('Recorded at: %s\n' % datetime.now())

Furthermore, I used the wrong path to python. I wrote /python3.6 instead of /python3 which I found through typing

which python3

in terminal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM