简体   繁体   English

无法通过 crontab 执行 python 2.7 脚本,但可以手动执行。 是什么赋予了?

[英]Unable to execute a python 2.7 script via crontab, but can execute it manually. What gives?

i have written a python script 2.7 version, in an Ubuntu OS it will successfully run if I execute it manually, but when I put it in a cronjob it will not work - You will get random library path or module not found error depending what you import/include.我编写了一个 python 脚本 2.7 版本,在 Ubuntu 操作系统中,如果我手动执行它,它将成功运行,但是当我将它放入 cronjob 时,它将无法工作 - 您将收到随机库路径或未找到模块的错误,具体取决于您的内容导入/包含。 I have read stackoverflow almost the same question but the solution provided still does not work for me.我已经阅读了几乎相同的问题 stackoverflow,但提供的解决方案仍然对我不起作用。 Python script not executing in crontab Python 脚本未在 crontab 中执行

It is just a simple error, but at first it is difficult to know why.这只是一个简单的错误,但一开始很难知道为什么。

Traceback (most recent call last):
File "/var/www/project/delete.py", line 263, in <module>
pyquery('new')
NameError: pq 'new_data' is not defined

Generally speaking (python) Script is location-sensitive.一般来说(python)脚本是位置敏感的。 This is related to always using absolute paths in a script, but not quite the same.这与在脚本中始终使用绝对路径有关,但并不完全相同。 Your cron job may need to cd to a specific directory where the script is stored before running it.在运行之前,您的 cron 作业可能需要 cd 到存储脚本的特定目录。

When Cronjob runs it uses your home directory as current directory.当 Cronjob 运行时,它使用您的主目录作为当前目录。 So if you were to put your script in your home directory, it will work.因此,如果您将脚本放在主目录中,它将起作用。 In this case the script was using a relative path, assuming that it was relative to the location of the script but it was in fact relative to the root of your home directory because that was the working directory that cron was using, which is why the script worked when it was in the root of my home directory.在这种情况下,脚本使用相对路径,假设它相对于脚本的位置,但实际上它相对于主目录的根目录,因为那是 cron 使用的工作目录,这就是为什么脚本在我的主目录的根目录下工作。

So if you have to run it in a directory other than your home directory, in your cronjob you will need to cd to your script directory and run it as in this example:因此,如果您必须在主目录以外的目录中运行它,则在您的 cronjob 中,您需要 cd 到您的脚本目录并运行它,如下例所示:

* * * * * cd /var/www/clientfolder/ && /usr/bin/python /var/www/clientfolder/your_python_script.py >> /var/www/clientfolder/your_python_script.log

it is important you understand why.了解原因很重要。 It should now work!它现在应该可以工作了!

If you have other issue not related to Script Execute Environment you may want to read this very good article CronJob not running如果您有其他与脚本执行环境无关的问题,您可能需要阅读这篇非常好的文章CronJob not running

Source: https://www.digitalocean.com/community/questions/unable-to-execute-a-python-script-via-crontab-but-can-execute-it-manually-what-gives资料来源: https : //www.digitalocean.com/community/questions/unable-to-execute-a-python-script-via-crontab-but-can-execute-it-manually-what-gives

Best of luck祝你好运

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

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