我正在尝试从 cron 运行 Python 脚本。我使用 crontab 以用户身份而不是 root 身份运行命令。我的 Python 脚本的 shebang 位于顶部#! /usr/bin/env python
我做到了chmod +x
它使脚本可执行。
该脚本在从 shell 运行时确实有效,但在使用 crontab 时则无效。我确实检查了/var/log/cron
文件并看到脚本运行但绝对没有任何来自stdout
or 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()
EDIT我知道出了什么问题了。我需要将绝对文件路径放入脚本中,否则它会写入我没有计划的某个目录。
好吧,我想这个帖子仍然会对谷歌员工有所帮助。
我使用一种解决方法来通过 cron 作业运行 python 脚本。事实上,Python 脚本需要通过 cron 作业小心处理。
所以我让一个 bash 脚本来处理这一切。
我创建了一个 bash 脚本,其中包含运行 python 脚本的命令。然后我安排一个 cron 作业来运行 bash 脚本。您甚至可以使用重定向器来记录执行 python 脚本的 bash 命令的输出。
例如
@reboot /home/user/auto_delete.sh
auto_delete.sh 可能包含以下行:-
#!/bin/sh
echo $(date) >> bash_cron_log.txt
/usr/bin/python /home/user/auto_delete.py >> bash_cron_log.txt
所以我不需要担心 Cron Jobs 在 python 脚本上崩溃。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)