实现crontab定时调用python脚本,以及command not found的问题

操作

1.修改 /etc/crontab文件
调用python脚本和其他sh的不同是:需要写清楚调用哪个python解释器
例如:
* 12 * * * root /usr/bin/python /home/admin/test.py
需要用/usr/bin/python 全路径指定.
另外需要在此前写root 表示调用账户.
2.增加日志
使用/home/admin/test.py.log 2>&1 把错误流重定向到标准输出流
全部配置如下:
* 12 * * * root /usr/bin/python /home/admin/test.py >> /home/admin/test.py.log 2>&1


问题

python脚本里调用了别的命令,如git命令,执行时可以执行,但crontab执行时显示command not found
比如我在python脚本里,subprocess.Popen来执行一个'git pull'命令.

def get_err_process_cmd(cmd):
    stdout, stderr = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE).communicate()
    print stdout
    return str(stderr)

# 直接 ./test.py可以顺利运行
err = get_err_process_cmd('git pull')

crontab配置后,则会是 binsh: git command not found
解决办法:
whereis git去找到git的安装路径,比如我的是 /usr/local/bin/git
然后在python脚本里替换:

git_home = '/usr/local/bin/git'
err = get_err_process_cmd(git_home +' pull')

这样crontab就能顺利执行

转载请注明来源,谢谢
原文地址:https://www.cnblogs.com/zhhiyp/p/10160754.html