Scheduling a python 3.6 script in using crontab/cron

无人久伴 提交于 2019-12-04 04:55:21

问题


I'm just setting up a cron tab/job on my Cent OS developement server.

Within my crontab I have the following. (Ignore the time setting, this was added about 15:32 UTC server time just to get the next scheduled run in).

34 15 * * * cd welcomeclient-0.0.5 && python3.6 main.py

In the command line cd welcomeclient-0.0.5 && python3.6 main.py works fine. welcomeclient-0.0.5 is under root in the droplet, and python3.6 is in /usr/bin.

Any suggestions?


回答1:


Try using absolute paths in your crontab command:

34 15 * * * cd /foo/bar/welcomeclient-0.0.5 && /usr/bin/python3.6 main.py

or, assuming the main.py does not also make use of relative paths inside of it :

34 15 * * */usr/bin/python3.6 /foo/bar/welcomeclient-0.0.5/main.py



回答2:


Looks like you're trying to change directory in crontab, just like omu_negru said you'll need to use full path instead. That's because crontab even if running under your name will not inherit your environmental variables such as $PATH.

Try this. First, go to the directory where your script is... and turn your main.py to an executable file so you don't have to call python main.py anymore. The simplest way to do so is...

$ chmod u+x main.py

Now if you do ls -l you'll see that you have "x" in the user section of permissions which will allow you to run it directly.

-rwxr--r-- 1 user user 0 Aug 17 17:55 main.py

Now you're ready to simplify crontab syntax to something like this...

34 15 * * * /foo/bar/welcomeclient-0.0.5/main.py 

I also like to capture the output from the script to a log file so it's easier to troubleshoot when things don't work our as planned, as follows:

34 15 * * * /foo/bar/welcomeclient-0.0.5/main.py & >> /foo/bar/main.log 

The log should be added to log rotation, otherwise it will keep filling up and eventually make your system run out of space, but that's another topic already addressed on this site.



来源:https://stackoverflow.com/questions/45740940/scheduling-a-python-3-6-script-in-using-crontab-cron

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!