Python自动重启系统
我需要使用 python 检测程序何时崩溃或未运行并重新启动它。 我需要一种不一定依赖于 python 模块作为父进程的方法。
我正在考虑实现一个 while 循环,该循环本质上是这样的
ps -ef | grep process name
,当找不到该进程时,它会启动另一个循环。 也许这不是最有效的方法。 我是 python 新手,所以可能已经有一个 python 模块可以做到这一点。
I need to detect when a program crashes or is not running using python and restart it. I need a method that doesn't necessarily rely on the python module being the parent process.
I'm considering implementing a while loop that essentially does
ps -ef | grep process name
and when the process isn't found it starts another. Perhaps this isn't the most efficient method. I'm new to python so possibly there is a python module that does this already.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
为什么要自己实现呢? 现有的实用程序,例如 daemon 或 Debian 的
start-stop-daemon
更有可能获得关于运行长期存在的服务器进程的其他困难的事情。无论如何,当您启动服务时,将其 pid 放入
/var/run/.pid
中,然后使您的ps
命令仅查找该进程 ID,并检查它是否是正确的过程。 在 Linux 上,您只需查看/proc//exe
即可检查它是否指向正确的可执行文件。Why implement it yourself? An existing utility like daemon or Debian's
start-stop-daemon
is more likely to get the other difficult stuff right about running long-living server processes.Anyway, when you start the service, put its pid in
/var/run/<name>.pid
and then make yourps
command just look for that process ID, and check that it is the right process. On Linux you can simply look at/proc/<pid>/exe
to check that it points to the right executable.请不要重新发明 init. 您的操作系统有能力做到这一点,几乎不需要任何系统资源,并且肯定会比您可以重现的任何东西做得更好、更可靠。
Classic Linux 有 /etc/inittab
Ubuntu 有 /etc/event.d (upstart)
OS X 已经 launchd
Solaris 有 smf
Please don't reinvent init. Your OS has capabilities to do this that require nearly no system resources and will definitely do it better and more reliably than anything you can reproduce.
Classic Linux has /etc/inittab
Ubuntu has /etc/event.d (upstart)
OS X has launchd
Solaris has smf
以下代码在给定的时间间隔内检查给定的进程,并重新启动它。
The following code checks a given process in a given interval, and restarts it.
也许你需要 http://supervisord.org
maybe you need http://supervisord.org
我自己没有尝试过,但是有一个 Python System Information 模块可以使用查找进程并获取有关它们的信息。 AFAIR 有一个 ProcessTable 类可用于检查正在运行的进程,但它似乎没有很好的文档记录......
I haven't tried it myself, but there is a Python System Information module that can be used to find processes and get information about them. AFAIR there is a
ProcessTable
class that can be used to inspect the running processes, but it doesn't seem to be very well documented...我会采用命令行路线(恕我直言,这更容易),只要您只每隔一两秒检查一次,与任何不到 10 年历史的系统上的可用处理相比,资源使用量应该是无限小的。
I'd go the command-line route (it's just easier imho) as long as you only check every second or two the resource usage should be infintesimal compared to the available processing on any system less than 10 years old.