分叉、守护进程和监视 python 脚本

Forking, daemonizing and monitoring a python script

我的 debian 服务器上有一个 python 脚本 sc.py。

我愿意:

你知道可以让我这样做的软件吗?

我不知道我是否必须在 python 方面(任何 python 模块或配置)寻找解决方案,或者是否有某个地方的 debian 软件包可以完成这项工作?

您可以使用 supervisord 来实现。

它为您守护 Python 个进程,还处理子进程。

如果这是一项 one-time 任务(也就是说,您不是在创建软件产品),我会 quick-and-dirty 结合使用 shell 脚本和终端多路复用器,例如 screen. For restarting processes that died (that is, they emitted an exit code other than 0), just use the shell.

例如像这样启动您的流程:

for i in n/*; do
    screen -d -m -L -S $i -t $i until python sc.py $i; do echo "Crashed with exit code $?.  Respawning.." >&2 ; sleep 1 ; done
done

这会

  • 为子目录 n/ 中的每个文件创建一个新屏幕 session 运行 您的脚本,
  • 重新启动您的 python 脚本,除非它成功退出(使用 Bash 的 until
  • 设置标题(-t)和session名称(-S)为输入文件名,
  • 并打开所有输出的日志记录,以便以后在出现问题时进行检查 (-L)。

然后您可以使用正常的屏幕命令,例如 screen -list 列出所有 运行 任务和 screen -r <session name> 查看 运行 session 输出。

我偶然发现的另一个进程管理器是 circus

如果你喜欢的话,它看起来更冒险;)

Web 界面比 supervisord 的更丰富:看到一些不错的 screenshots