【发布时间】:2014-11-20 20:50:49
【问题描述】:
我正在尝试从 cron 运行 Python 脚本。我正在使用 crontab 以用户而不是 root 身份运行命令。我的 Python 脚本在顶部有 #! /usr/bin/env python 的 shebang,我做了 chmod +x 它以使脚本可执行。
该脚本在从 shell 运行时确实有效,但在使用 crontab 时无效。我确实检查了/var/log/cron 文件并看到脚本运行但绝对没有来自stdout 或stderr 的任何地方打印。
最后,我制作了一个打印日期和字符串的小脚本,并且每分钟都调用它,但这个其他脚本没有。我不知道为什么我会得到这些可变的结果......
这是我在crontab的条目
SHELL=/bin/bash
#min #hour day-of-month month day-of-week command
#-------------------------------------------------------------------------
*/5 * * * * /path/to/script/script.py
这是我的脚本的源代码,它不会从 crontab 运行,但会在调用时从它所在的 shell 运行,如 ./script.py。顺便说一句,在我使用chmod +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()
编辑 我弄清楚出了什么问题。我需要将绝对文件路径放在脚本中,否则它会写入我没有计划的某个目录。
【问题讨论】:
-
请附上相关代码——这将有助于我们回答。
-
shell 环境之间通常存在其他可能影响您的脚本的差异:不同的
PYTHONPATH是一种可能性。您可能希望在cron下运行一个脚本,该脚本仅打印其环境,并将其与基于 shell 手动执行的预期进行比较。 -
你在重定向stdout和stderr吗?您希望看到它们出现在哪里?
-
请发布您如何在 crontab 中创建条目。例如:
5 5 * * * sript_to_run。所以它会帮助我们弄清楚,是cron条目还是代码的问题。大多数情况下,如何在 cron 中输入是一个问题。 -
我看到你正在使用
/usr/bin/env python。这假设 python 在$PATH中。 python在哪里添加到路径中?如果在您的 .profile 中,那么您可能会发现它没有运行。使用/usr/bin/python或任何你的python 路径更安全。