linux - 通过 crontab 终止后运行 python 程序

标签 linux bash ubuntu cron

我有一个python网页抓取程序,程序终止后需要不断抓取。我的技术如下

crontab -e(设置)

* * * * * /home/ahmed/Desktop/run.sh

运行.sh

    TMP_FILE=/tmp/i_am_running
    [ -f $TMP_FILE ] && exit
    touch $TMP_FILE
    /usr/bin/python /home/ahmed/Desktop/python.py
    rm $TMP_FILE

bash 代码一定有问题,或者可能是我在 crontab 中的命令有误。该程序没有运行。请指导


根据 Mark 的建议,我修改了脚本

#!/bin/bash
PATH=$PATH:/bin:/usr/bin

date +'%H:%M:%S Started' >> /home/ahmed/Desktop/log.txt

TMP_FILE=/tmp/i_am_running
[ -f $TMP_FILE ] && exit
touch $TMP_FILE

date +'%H:%M:%S Starting Python' >> /home/ahmed/Desktop/log.txt
/usr/bin/python /home/ahmed/Desktop/python.py
rm $TMP_FILE

date +'%H:%M:%S Ended' >> /home/ahmed/Desktop/log.txt

我使用的 cron 命令是 * * * * */home/ahmed/Desktop/run.sh

创建的日志文件是这个

15:21:01 Started
15:21:02 Starting Python
15:22:02 Started
15:23:01 Started
15:24:01 Started
15:24:30 Ended
15:25:01 Started
15:25:01 Starting Python
15:26:01 Started
15:27:18 Started
15:28:01 Started
15:29:01 Started
15:30:01 Started
15:31:01 Started
15:31:16 Ended
15:32:01 Started
15:32:01 Starting Python
15:33:01 Started
15:34:01 Started

程序似乎在结束前重新启动。日志文件应该有开始程序、开始、结束、开始程序、开始、结束等。

有人可以指导我吗?

最佳答案

您是否使您的脚本可执行?

chmod +x /home/ahmed/Desktop/run.sh

在你的脚本中放置一个正确的 shebang 和 PATH,这样它就这样开始:

 #!/bin/bash
 PATH=$PATH:/bin:/usr/bin

从命令行自行尝试您的脚本

/home/ahmed/Desktop/run.sh

如果这不起作用,请更改 shebang 行以在末尾添加 -xv

#!/bin/bash -xv 

检查/tmp/i_am_running 是否存在

检查你的 cron 日志

grep CRON /var/log/syslog

考虑更改您的脚本,以便您可以查看它何时启动和/或它是否实际运行了您的 python:

#!/bin/bash
PATH=$PATH:/bin:/usr/bin

date +'%H:%M:%S Started' >> /home/ahmed/Desktop/log.txt

TMP_FILE=/tmp/i_am_running
[ -f $TMP_FILE ] && exit
touch $TMP_FILE

date +'%H:%M:%S Starting Python' >> /home/ahmed/Desktop/log.txt
/usr/bin/python /home/ahmed/Desktop/python.py
rm $TMP_FILE

date +'%H:%M:%S Ended' >> /home/ahmed/Desktop/log.txt

对了,不知道18:01跑一次怎么算“连续刷”?

关于linux - 通过 crontab 终止后运行 python 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22605361/

相关文章:

ubuntu - 简单 Hadoop Map Reduce 中的错误

django - 我如何将 Python 图像库安装到 django 环境?

c++ - boost::mpi 阻塞 IO 不会被 linux 信号中断

linux - 使用新的消费者API时如何删除属于主题T的消费者组C

bash - 如何在 Windows 上的 Bash 的 vim 中设置 "copy to clipboard"?

linux - 在 linux 中运行不同名称的相同程序

python - 如何在 python 中保持子进程运行并持续向其提供输出?

linux - 将 Linux 桌面中的工作区变成永久终端

linux - 比较两个文件并仅获取差异 - shell 脚本

python - -bash : !/usr/bin/env: 找不到事件