實現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

問題

python腳本里調用了別的命令,如git命令,執行時能夠執行,但crontab執行時顯示command not found
好比我在python腳本里,subprocess.Popen來執行一個'git pull'命令.git

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腳本里替換:shell

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

這樣crontab就能順利執行日誌

相關文章
相關標籤/搜索