bash Python 脚本未在 cron 中运行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26049459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:24:56  来源:igfitidea点击:

Python Script not running in cron

pythonbashshellcron

提问by user3870315

I am trying to run a Python script from cron. I am using crontab to run the command as a user instead of root. My Python script has the shebang at the top #! /usr/bin/env pythonand I did chmod +xit to make the script executable.

我正在尝试从 cron 运行 Python 脚本。我正在使用 crontab 以用户而不是 root 身份运行命令。我的 Python 脚本在顶部有 shebang,#! /usr/bin/env python我这样做chmod +x是为了使脚本可执行。

The script does work when running it from a shell but not when using crontab. I did check the /var/log/cronfile and saw that the script runs but that absolutely nothing from stdoutor stderrprints anywhere.

该脚本在从 shell 运行时有效,但在使用 crontab 时无效。我确实检查了/var/log/cron文件并看到脚本运行但绝对没有任何地方stdoutstderr任何地方打印。

Finally, I made a small script that prints the date and a string and called that every minute that worked but this other script does not. I am not sure why I am getting these variable results...

最后,我制作了一个打印日期和字符串的小脚本,并在每分钟有效的时候调用它,但另一个脚本没有。我不知道为什么我会得到这些可变的结果......

Here is my entry in crontab

这是我的条目 crontab

SHELL=/bin/bash



#min    #hour   day-of-month    month   day-of-week     command
#-------------------------------------------------------------------------
*/5     *       *                *        *             /path/to/script/script.py

Here is the source code of my script that will not run from crontab but will run from the shell it is in when called like so ./script.py. The script is executable after I use the chmod +xcommand on it, by the way...:

这是我的脚本的源代码,它不会从 crontab 运行,但会从它所在的 shell 运行,就像这样调用./script.pychmod +x顺便说一句,在我对它使用命令后,该脚本是可执行的...:

#! /usr/bin/env python

#create a file and write to it
import time

def create_and_write():
    with open("py-write-out.out", "a+") as w:
        w.write("writing to file. hello from python. :D\n")
        w.write("the time is: " + str(time.asctime()) + "\n")
        w.write("--------------------------------\n")


def main():
    create_and_write()

if __name__ == "__main__":
    main()

EDITI figured out what was going wrong. I needed to put the absolute file paths in the script otherwise it would write to some directory I had not planned for.

编辑我想出了什么问题。我需要将绝对文件路径放在脚本中,否则它会写入我没有计划的某个目录。

回答by cppcoder

You can resolve this yourself by following these steps:

您可以按照以下步骤自行解决此问题:

  1. Modify the cron as /path/to/script/script.py > /tmp/log 2> &1
  2. Now, let the cron run
  3. Now read the file /tmp/log
  4. You will find out the reason of the issue you are facing, so that you can fix it.
  1. 将 cron 修改为 /path/to/script/script.py > /tmp/log 2> &1
  2. 现在,让 cron 运行
  3. 现在读取文件 /tmp/log
  4. 您将找出您面临的问题的原因,以便您可以解决它。

In my experience, the issue is mostly with the environment.
In cron, the env variables are not set. So you may have to explicitly set the env for your script in cron.

根据我的经验,问题主要与环境有关。
在 cron 中,未设置 env 变量。因此,您可能必须在 cron 中为您的脚本显式设置 env。

回答by user2593869

Ok, I guess this thread is still going to help googlers.
I use a workaround to run python scripts with cron jobs. In fact, python scripts need to be handled with delicate care with cron job.
So I let a bash script take care of all of it.
I create a bash script which has the command to run the python script. Then I schedule a cron job to run bash script. You can even use a redirector to log the output of bash command executing the python script.
For example

好的,我想这个线程仍然会帮助谷歌员工。
我使用一种解决方法来运行带有 cron 作业的 python 脚本。事实上,python 脚本需要在 cron 作业中小心翼翼地处理。
所以我让一个 bash 脚本来处理这一切。
我创建了一个 bash 脚本,它具有运行 python 脚本的命令。然后我安排了一个 cron 作业来运行 bash 脚本。您甚至可以使用重定向器来记录执行 python 脚本的 bash 命令的输出。
例如

@reboot /home/user/auto_delete.sh

auto_delete.sh may contain following lines:-

auto_delete.sh 可能包含以下几行:-

#!/bin/sh
echo $(date) >> bash_cron_log.txt
/usr/bin/python /home/user/auto_delete.py >> bash_cron_log.txt

So I don' need to worry about Cron Jobs crashing on python scripts.

所以我不需要担心 Cron Jobs 在 python 脚本上崩溃。

回答by sprite

Another reason may be that the way we judged executed or not executed is wrong.

另一个原因可能是我们判断执行或不执行的方式是错误的。

回答by user2593869

I would like to emphasise one more thing. I was trying to run a python script in cron using the same trick (using shell script) and this time it didn't run. It was @reboot cron. So I used redirection in crontab as I mentioned in one of the above comments. And understood the problem. I was using lot many file handlers in python script and cron runs the script from user's home directory. In that case python could not find the files used for file handlers and will crash.

What I used for troubleshooting was that I created a crontab as below. It would run the start.sh and throw all the stderror or stdoutput to file status.txt and I got error in status.txt saying that the file I used for file handler was not found. That was right because python script was executed by cron from user's home directory and then the script starts searching for files in home directory only.

我还要强调一件事。我试图使用相同的技巧(使用 shell 脚本)在 cron 中运行 python 脚本,但这次它没有运行。这是@reboot cron。因此,正如我在上述评论之一中提到的那样,我在 crontab 中使用了重定向。并了解问题所在。我在 python 脚本中使用了很多文件处理程序,cron 从用户的主目录运行脚本。在这种情况下,python 找不到用于文件处理程序的文件并且会崩溃。

我用于故障排除的是我创建了一个 crontab,如下所示。它会运行 start.sh 并将所有 stderror 或 stdoutput 扔到文件 status.txt 中,我在 status.txt 中收到错误,说找不到我用于文件处理程序的文件。这是对的,因为 python 脚本是由 cron 从用户的主目录执行的,然后脚本开始只在主目录中搜索文件。

@reboot /var/www/html/start.sh > /cronStatus/status.txt 2>&1

This will write everything happening during cron execution to status.txt file. You can see the error over there. I will again advice running python scripts using bash scripts for cronjobs.

SOLUTION:- Either you use full path for all the files being used in script (which wasn't feasible for me, since I don't want script to be location dependent). Or you execute script from correct directory So I created my cron as below-

这会将 cron 执行期间发生的所有事情写入 status.txt 文件。你可以在那里看到错误。我将再次建议使用 bash 脚本为 cronjobs 运行 python 脚本。

解决方案:- 要么为脚本中使用的所有文件使用完整路径(这对我来说不可行,因为我不希望脚本依赖于位置)。或者你从正确的目录执行脚本所以我创建了我的 cron 如下 -

@reboot cd /var/www/html/ && /var/www/html/start.sh

This cron will first change directory to correct location and then start the script. Now I don't have to worry about hardcoding full path for all files in script. Yeah, it may sound being lazy though ;)
And my start.sh looks like-

此 cron 将首先将目录更改为正确的位置,然后启动脚本。现在我不必担心脚本中所有文件的硬编码完整路径。是的,虽然听起来很懒惰 ;)
而我的 start.sh 看起来像-

#!/bin/sh
/usr/bin/python /var/www/html/script.py

Hope it helps
Regards,
Kriss

希望它有助于
问候,
克里斯

回答by sromano

I had a similar issue but with a little bit different scenario: I had a bash script (run.sh) and a Python script (hello.py). When I typed

我有一个类似的问题,但场景略有不同:我有一个 bash 脚本(run.sh)和一个 Python 脚本(hello.py)。当我打字

sh run.sh

from the script directory, it worked; if I added the sh run.shcommand in my crontab, it did not work.

从脚本目录,它工作;如果我在我的 crontab 中添加了sh run.sh命令,它不起作用。

To troubleshoot the issue I added the following line in my run.shscript:

为了解决这个问题,我在run.sh脚本中添加了以下行:

printenv > env.txt

In this way you are able to see the environment variable used when you (or the crontab) run the script. By analyzing the differences between the env.txtgenerated from the manual run and the crontab run I noticed that the PWDvariable was different. In my case I was able to resolve by adding the following line at the top of my .shscript:

通过这种方式,您可以看到您(或 crontab)运行脚本时使用的环境变量。通过分析手动运行生成的env.txt和 crontab 运行生成的差异,我注意到PWD变量是不同的。在我的情况下,我能够通过在我的.sh脚本顶部添加以下行来解决:

cd /PYTHON_SCRIPT_ABSOLUTE_PATH/

Hope this could help you!

希望这可以帮助你!