问题描述
我试图由cron Python脚本。我使用crontab来运行该命令为用户而不是根源。我的Python脚本有家当在顶部#!在/ usr /斌/包膜蟒蛇
和我做使用chmod + X
它使脚本可执行。
I am trying to run a Python script from cron. I am using crontab to run the command as a user instead of root. My Python script has the shebang at the top #! /usr/bin/env python
and I did chmod +x
it to make the script executable.
该脚本并从shell中运行它的时候,但使用crontab的时候不起作用。我做了检查 /无功/日志/ cron的
文件,看到脚本运行但绝对没有从标准输出
或标准错误
打印任何地方。
The script does work when running it from a shell but not when using crontab. I did check the /var/log/cron
file and saw that the script runs but that absolutely nothing from stdout
or stderr
prints anywhere.
最后,我做了一个小的脚本,打印日期和一个字符串,并呼吁每一分钟的工作,但这个其它脚本不。我不知道为什么我得到这些变量的结果...
Finally, I made a small script that prints the date and a string and called that every minute that worked but this other script does not. I am not sure why I am getting these variable results...
下面是我在输入的crontab
SHELL=/bin/bash
#min #hour day-of-month month day-of-week command
#-------------------------------------------------------------------------
*/5 * * * * /path/to/script/script.py
下面是我的脚本源$ C $ C,不会从crontab中运行,但会从它在叫的时候像这样 ./ script.py
。该脚本是可执行的我用使用chmod + X
命令后,就可以了,顺便说一句...:
Here is the source code of my script that will not run from crontab but will run from the shell it is in when called like so ./script.py
. The script is executable after I use the chmod +x
command on it, by the way...:
#! /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()
修改
我想通了什么事情错了。我需要把绝对的文件路径中的脚本,否则会写一些目录中我还没有计划。
EDITI figured out what was going wrong. I needed to put the absolute file paths in the script otherwise it would write to some directory I had not planned for.
推荐答案
您可以将此自己被以下步骤解决:
You can resolve this yourself by following these steps:
- 修改的cron为
/path/to/script/script.py>的/ tmp /日志2 - ; &放大器; 1
- 现在,让我们的cron运行
- 现在,读取文件
的/ tmp /日志
- 您会发现,你所面对的,这样就可以解决它问题的原因。
在我的经验,这个问题主要是与环境。结果
cron中的ENV变量未设置。所以,你可能要明确设置为ENV的cron中的脚本。
In my experience, the issue is mostly with the environment.
In cron, the env variables are not set. So you may have to explicitly set the env for your script in cron.
这篇关于Python脚本不运行的cron的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!