简体   繁体   English

Python 脚本在 cron 作业中运行时引发错误,但不会在其他时间引发错误

[英]Python script elicits error when run in cron job but at no other time

I have a shell script that includes execution of a python script.我有一个包含执行 python 脚本的 shell 脚本。 When I run it manually in terminal, it works fine.当我在终端中手动运行它时,它工作正常。 However when I execute the shell script in a cron job, the python script fails.但是,当我在 cron 作业中执行 shell 脚本时,python 脚本失败。

The error is apparently triggered while functions are being imported from module1 into module2.该错误显然是在函数从 module1 导入到 module2 时触发的。 The function referenced by the error is not among the functions being imported, nor does the function where the syntax error is supposed to be elicit an error when it is executed by itself.错误引用的函数不在被导入的函数中,语法错误的函数本身执行时也不会引发错误。

Here's the error that gets logged when I run the cron job:这是我运行 cron 作业时记录的错误:

File "/Users/me/module2.py", line 5, in <module>
    from module1 import consolidate_rankings, build_all
  File "/Users/me/module1.py", line 159
    things = {row["thing"]: row for row in rows}
                                          ^

SyntaxError: invalid syntax

The module2 script is pretty straightforward: module2 脚本非常简单:

#!/usr/bin/env python 

from module1 import consolidate_rankings, build_all

consolidate_rankings()
build_all()

Here's the line that calls this in the shell script:这是在 shell 脚本中调用它的行:

python /Users/me/module2.py python /Users/me/module2.py

Anyone have any idea what's going on here?有人知道这里发生了什么吗?

You are probably running your script from cron with a different version of Python that doesn't support the dictionary comprehension syntax.您可能正在使用不支持字典理解语法的不同版本的 Python 从 cron 运行您的脚本。

To fix this, either explicitly add your desired Python version in the shebang line:要解决此问题,请在 shebang 行中明确添加所需的 Python 版本:

#!/usr/bin/env python2.7

or launch your script from cron through the correct command:或通过正确的命令从 cron 启动您的脚本:

* * * * /usr/bin/python2.7 /path/to/script.py

I solved this by declaring my local env in the crontab itself (since the above didn't help):我通过在 crontab 本身中声明我的本地环境来解决这个问题(因为以上没有帮助):

SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/usr/local/sifi/bin:/home/username/.local/bin:/home/username/bin:/home/username

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

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