【问题标题】:How to run a python script with CRON on Debian?如何在 Debian 上使用 CRON 运行 python 脚本?
【发布时间】:2018-03-20 07:09:09
【问题描述】:

我想在每 X 小时运行一次脚本,这就是为什么我写了一个 BASH(命名为 mybash.sh),这样调用这个脚本:

#!/bin/bash PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/sbin:/usr/src/Python-2.7.13 python /usr/src/Python-2.7.13/test1.py

这个 bash 文件在我的 /usr/src/Python-2.7.13 和我的 test1.py 中。 如果我正在运行sh mybash.sh,它正在运行!我也做了chmod a+x mybash。

进入crontab-e我写道:

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/sbin:/usr/src/Python-2.7.13 
* * * * * /usr/src/Python-2.7.13/mybash.sh 2>&1

如果我打电话给crontab-l,我会在那里看到这些行。

但我的脚本没有运行..我错过了什么?

EDIT1 - cat /etc/crontab

# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user  command
17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly
25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6    * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6    1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
#

【问题讨论】:

  • 你为什么把python脚本打包成bash脚本?
  • 因为我读到了,这是使用 cron 运行 .py 文件的常用过程。
  • 脚本的作用是什么?还有,你为什么不用Debian自带的python解释器?
  • 脚本是网页抓取(打开一些网站),我该如何使用?
  • 脚本是否需要 GUI? (打开浏览器?)。你在/var/log/cron.log 有什么?正在执行 cron 脚本的用户在 ${MAIL} 文件中得到了什么? (回复时请使用“@umläute”以便我收到通知)

标签: python bash cron debian


【解决方案1】:

你可以简单地在 crontab 中调用 python

* * * * * [path/to/py/executable] [path/to/py/script]

由于 cron 环境中的变量受限,请记住指定可执行文件的完整路径。

【讨论】:

  • 所以我可能要写这个? : * * * * * /usr/src/Python-2.7.13/mybash.sh /usr/src/Python-2.7.13/test.py ?
  • 不,我的意思是,例如* * * * * /usr/bin/python /usr/src/Python-2.7.13/test.py
  • 既不输出邮件日志?你确定你找到了正确的 python 路径吗?如果你把 /usr/bin/python (或其他)放在一个 shell 中,它会产生 Python 解释器?
  • 我确定,因为我的 python 程序以 #!/usr/bin/python 和 #!/bin/sh 开头。所以我不知道为什么它无法启动
  • 所以,我不能帮助你,因为它应该很好......只是一个愚蠢的问题,你是否在 crontab 的末尾插入了空白?如果不是太长,可以在这里发布 cat /etc/crontab 的结果
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-26
  • 2011-05-28
  • 2019-05-14
  • 2015-03-16
  • 2011-09-03
  • 1970-01-01
相关资源
最近更新 更多