python 在 crontab 中的调用

python 在 crontab 中的调用

  使用python写了一个脚本,手动执行没有问题。需要自动运行,所以要配置到crontab中。举例脚本位置“/Data/script/test.py” ,其中包含读取操作系统、读取配置文件、写日志操作,使用root用户每5分钟执行一次。最初配置为:

*/5 * * * * /usr/local/bin/python /Data/script/test.py >/dev/null

  需要注意的是“*/5 * * * *”中间要用空格分隔。“/usr/local/bin/python”要根据使用的python脚本安装位置填写,通过观察定时任务失败。
  分析原因,crontab运行时的环境变量与ssh登录的环境变量不同,导致读取配置目录和文件失败。解决方法,写一个shell调用脚本,将脚本放在crontab中。脚本有一个参数“start”。
shell脚本为test.sh:

#! /bin/bash
#
# crontab shell python
#
# www.simonzhang.net
# email:simon-zzm@163.com
#
### END INIT INFO

. /etc/profile
cd /Data/script/

case "$1" in
  start)
      /usr/local/bin/python /Data/script/test.py start &
     ;;
  test)
      /usr/local/bin/python /Data/script/test.py test &
      ;;
  *)
        echo $"Usage: $0 {start|test}"
        exit 1
esac

exit 1

将脚本配置到crontab中运行成功,配置为:

*/5 * * * * /bin/sh /Data/script/test.sh start >/dev/null

发表评论

电子邮件地址不会被公开。 必填项已用*标注