简体   繁体   中英

Python scripts couldn't work with crontab

I'm new to stackoverflow and really hope to get answers to my question about crontab. I'm using MacbookAir in BigSur(don't know if it affects)And my crontab just couldn't run python scripts below.

f = open("test_crontab.txt",'w+')
f.write("Success")
f.close()

But I could run this script with Spyder. I could edit crontab with crontab -e, and my code in vi crontab was

13 01 * * * /bin/zsh  /Users/myusername/Documents/Lynn\'s\ Python\ work/shopee/test.py >>/Users/myusername/Desktop/out.log 2>>/Users/tzulingkuo/Desktop/err.log

But it failed to generate txt file.

The messages in err.log were like below:

/Users/*myusername*/Documents/Lynn's Python work/shopee/test.py:5: missing end of string
/Users/*myusername*/Documents/Lynn's Python work/shopee/test.py:6: unknown username ''

I've searched stackoverflow for two nights and couldn't find the solution. I major in finance and I have no friends studying computer science.

Could anyone help me 🥺 Any help is reaaaaally appreciated!

Since that's a python script, you need to run it in python, not /bin/zsh. zsh is trying to interpret it as a shell script, but the syntax is all wrong, so you get errors.

The simplest way to fix this to replace /bin/zsh in your crontab entry with /usr/bin/python (assuming you're using the built-in Python version 2; if you have installed Python version 3 and want to use that, run which python at the command line to find its path).

But it's generally better to add a shebang line to your python script, and let that control how it's run. Add this as the very first line of the script:

#!/usr/bin/python

(Again, if you want to use Python 3, replace the path part with the path for the Python 3 interpreter.) Then make the script executable with chmod +x /Users/myusername/Documents/Lynn\\'s\\ Python\\ work/shopee/test.py , and just remove the /bin/zsh part from the crontab entry.

BTW, you're probably going to have trouble with paths. By default, cron jobs run with their working directory set to your home directory, so when the script opens test_crontab.txt , that's going to be interpreted as /Users/myusername/test_crontab.txt . If you want it down in the Documents/Lynn's Python work/shopee directory, you'll have to specify that explicitly.

You may also run into trouble with missing environment variables. If you're setting any environment variables in your shell initialization scripts that configure Python, add libraries, etc, those won't be set up in the cron job's environment.

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