[英]How can I keep my python-daemon process running or restart it on fail?
I have a python3.9 script I want to have running 24/7.我有一个 python3.9 脚本,我想全天候运行 24/7。 In it, I use python-daemon to keep it running like so:
在其中,我使用python-daemon来保持它的运行,如下所示:
import daemon
with daemon.DaemonContext():
%%script%%
And it works fine but after a few hours or days, it just crashes randomly.它工作正常,但几个小时或几天后,它只是随机崩溃。 I always start it with
sudo
but I can't seem to figure out where to find the log file of the daemon process for debugging.我总是用
sudo
启动它,但我似乎无法弄清楚在哪里可以找到用于调试的守护进程的日志文件。 What can I do to ensure logging?我可以做些什么来确保日志记录? How can I keep the script running or auto-restart it after crashing?
如何在崩溃后保持脚本运行或自动重启?
If you really want to run a script 24/7 in background, the cleanest and easiest way to do it would surely be to create a systemd service.如果您真的想在后台全天候 24/7 运行脚本,那么最干净、最简单的方法肯定是创建一个 systemd 服务。
There are already many descriptions of how to do that, for example here .已经有很多关于如何做到这一点的描述,例如这里。
One of the advantages of systemd
, in addition to being able to launch a service at startup, is to be able to restart it after failure. systemd
的优点之一,除了能够在启动时启动服务外,还可以在失败后重新启动它。
Restart=on-failure
If all you want to do is automatically restart the program after a crash, the easiest method would probably be to use a bash script.如果您只想在崩溃后自动重启程序,最简单的方法可能是使用 bash 脚本。
You can use the until loop
, which is used to execute a given set of commands as long as the given condition evaluates to false.您可以使用
until loop
,它用于执行一组给定的命令,只要给定条件的计算结果为 false。
#!/bin/bash
until python /path/to/script.py; do
echo "The program crashed at `date +%H:%M:%S`. Restarting the script..."
done
If the command returns a non zero exit-status, then the script is restarted.如果命令返回非零退出状态,则脚本将重新启动。
I would start with familiarizing myself with those two questions:我将从熟悉这两个问题开始:
Looks like you need a supervisor that will make sure that your script/daemon is still running.看起来你需要一个主管来确保你的脚本/守护进程仍在运行。 You can take a look at supervisord .
你可以看看supervisord 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.