crontab python子进程和服务重启 [英] crontab python subprocess and service restart
问题描述
我有一个小的python代码重新启动nginx它不存在。
当我运行 sudo python monitor_server.py
一切正常。
当我尝试使用根cron( sudo crontab -e
)用以下行代替它:
* * * * * python /root/monitor_server.py> /var/log/my_monitor/cron_log.log 2>& 1
我获得:
I have a small python code that restarts nginx on it's not existing.
When I run sudo python monitor_server.py
all is fine.
When I tried to cron it with root cron (sudo crontab -e
) with the line:
* * * * * python /root/monitor_server.py > /var/log/my_monitor/cron_log.log 2>&1
I get:
Traceback (most recent call last):
File "/root/monitor_server.py", line 19, in <module>
restart_service('mongod')
File "/root/monitor_server.py", line 10, in restart_service
subprocess.call(command, shell=False)
File "/usr/lib64/python2.6/subprocess.py", line 478, in call
p = Popen(*popenargs, **kwargs)
File "/usr/lib64/python2.6/subprocess.py", line 642, in __init__
errread, errwrite)
File "/usr/lib64/python2.6/subprocess.py", line 1234, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
代码:
def restart_service(name):
command = ['service', name, 'restart'];
#shell=FALSE for sudo to work.
subprocess.call(command, shell=False)
if __name__ == '__main__':
try:
f = urllib2.urlopen("<healthcheck URL>")
except (urllib2.HTTPError, urllib2.URLError) as e:
logging.log(logging.ERROR, 'restarting server')
restart_service('nginx')
推荐答案
尝试使用绝对路径调用命令,
Try calling the command using absolute path, as you call it without shell and under another user account, some commands are not available without specifying absolute path.
首先找到命令所在的位置:
First find, where is the command located:
$ which service
/usr/sbin/service
b $ b
然后将代码更改为:
Then change your code to:
def restart_service(name):
command = ['/usr/sbin/service', name, 'restart'];
#shell=FALSE for sudo to work.
subprocess.call(command, shell=False)
这篇关于crontab python子进程和服务重启的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!