操作
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配置后,則會是 bin\sh: 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就能順利執行