简体   繁体   English

使用crontab / cron计划python 3.6脚本

[英]Scheduling a python 3.6 script in using crontab/cron

I'm just setting up a cron tab/job on my Cent OS developement server. 我只是在我的Cent OS开发服务器上设置cron选项卡/作业。

Within my crontab I have the following. 在我的crontab中,我有以下内容。 (Ignore the time setting, this was added about 15:32 UTC server time just to get the next scheduled run in). (忽略时间设置,这是为了获得下一次预定运行时间而在UTC服务器时间中添加的大约15:32)。

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. 在命令行中,使用cd welcomeclient-0.0.5 && python3.6 main.py可以正常工作。 welcomeclient-0.0.5 is under root in the droplet, and python3.6 is in /usr/bin . welcomeclient-0.0.5位于welcomeclient-0.0.5根目录下,而python3.6位于/usr/bin

Any suggestions? 有什么建议么?

Try using absolute paths in your crontab command: 尝试在crontab命令中使用绝对路径:

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 : 或者,假设main.py也没有利用其中的相对路径:

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

Looks like you're trying to change directory in crontab, just like omu_negru said you'll need to use full path instead. 似乎您正在尝试更改crontab中的目录,就像omu_negru所说的那样,您将需要使用完整路径。 That's because crontab even if running under your name will not inherit your environmental variables such as $PATH. 这是因为crontab即使以您的名字运行也不会继承您的环境变量,例如$ 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. 首先,转到脚本所在的目录...,然后将main.py转换为可执行文件,这样就不必再调用python main.py了。 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. 现在,如果执行ls -l,将在权限的用户部分看到“ x”,您可以直接运行它。

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

Now you're ready to simplify crontab syntax to something like this... 现在您已经准备好将crontab语法简化为这样的东西...

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. 应该将日志添加到日志轮换中,否则它将不断填满并最终使您的系统空间不足,但这是此站点上已经解决的另一个主题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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