實現crontab定時調用python腳本,以及command not found的問題
阿新 • • 發佈:2018-12-22
腳本 local pipe 執行 一個 tro 解決辦法 nic HERE
***
操作
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就能順利執行
實現crontab定時調用python腳本,以及command not found的問題