微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

bash – 如果Python脚本被终止或死亡,如何自动重启它

我正在我的Ubuntu机器(12.04)中运行我的Python脚本,就像这样 –

nohup python testing.py > test.out &

现在,有可能在某些阶段我的上述Python脚本会因任何原因而死亡.

所以我想在bash shell脚本中有一些cron代理,如果因为某种原因被杀死,它可以自动重启我上面的Python脚本.

这可能吗?如果是,那么解决这类问题的最佳方法是什么?

更新:

在创建了像这样的testing.conf文件之后 –

chdir /tekooz
exec python testing.py
respawn

我在sudo命令下运行启动它,但我看不到使用ps ax后面运行的进程?

root@bx13:/bezook# sudo start testing
testing start/running, process 27794
root@bx13:/bezook# ps ax | grep testing.py
27806 pts/3    S+     0:00 grep --color=auto testing.py

知道为什么px ax没有给我看任何东西吗?我如何检查我的程序是否正在运行?

这是我的python脚本 –

#!/usr/bin/python
while True:
    print "Hello World"
    time.sleep(5)

解决方法:

在Ubuntu上(直到14.04,16.04及以后使用systemd)可以使用upstart这样做,比cron作业更好.您在/ etc / init中放置了配置设置,并确保指定respawn

它可以是一个最小的文件/etc/init/testing.conf(以root身份编辑):

chdir /your/base/directory
exec python testing.py
respawn

您可以使用/your/base/directory/testing.py进行测试:

from __future__ import print_function

import time

with open('/var/tmp/testing.log', 'a') as fp:
    print(time.time(), 'done', file=fp)
    time.sleep(3)

并开始于:

sudo start testing

并按照以下内容(在另一个窗口中)进行操作:

tail -f /var/tmp/testing.log

并停止:

sudo stop testing

您还可以添加[start on] [2]以使命令在系统启动时启动.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐