我的crontab -e
中有这个 * * * * * /usr/bin/python /home/backups/database/_scripts/example.py > /home/backups/database/_scripts/output.txt
example.py写入文件
import os
import time
import datetime
datetime = time.strftime('%m%d%Y-%H%M%S')
with open("test.txt", "a") as myfile:
myfile.write(datetime + "\n")
我在命令行上运行了它,它运行/usr/bin/python /home/backups/database/_scripts/example.py
我做错了什么?
答案 0 :(得分:1)
尝试添加
#!/usr/bin/env python
在脚本开头,设置执行权限,并将contrab条目更改为:
* * * * * /home/backups/database/_scripts/example.py > /home/backups/database/_scripts/output.txt
根据contrab的手册页示例:
# use /bin/sh to run commands, overriding the default set by cron
SHELL=/bin/sh
# mail any output to `paul', no matter whose crontab this is
MAILTO=paul
#
# run five minutes after midnight, every day
5 0 * * * $HOME/bin/daily.job >> $HOME/tmp/out 2>&1*
正如您所见,cron默认使用给定的SHELL,在示例中,它更改为 SHELL = / bin / sh 。显然,系统默认情况下,shell不会将/usr/bin/python
识别为脚本。
所以,你可以
#!/usr/bin/env python
行和执行权限的脚本。注意:我不知道cron是否可以检测到您正在尝试运行python脚本并自行调用python解释器。
答案 1 :(得分:1)
我猜您的test.txt
文件位于/home/backups/database/_scripts/
更改
with open("test.txt", "a") as myfile:
myfile.write(datetime + "\n")
到
with open("/home/backups/database/_scripts/test.txt", "a") as myfile:
myfile.write(datetime + "\n")