作为系统单元运行的python应用程序的信号处理程序实用程序
systemd-stopper的Python项目详细描述
systemd-stopper是一个小型库,用于在以systemd单位运行的python应用程序中方便地处理systemctl stop操作。由于使用systemd运行python进程很简单,因此处理stop命令也应该很简单。
快速启动
考虑以下定义my_app.service的单元文件:
[Unit] Description=Cool Python Unit After=network.target [Service] ExecStart=/usr/bin/python3 /home/user/my_app.py KillMode=Process [Install] WantedBy=multi-user.target
要通过systemctl stop my_app优雅地停止应用程序,我们必须为SIGTERM信号实现一个信号处理程序。直接使用标准库中的signal模块有点低级,特别是如果应用程序是多线程的,或者必须在多个应用程序中实现信号处理。
systemd-stopper允许直接处理停止事件,例如在具有简单主循环的应用程序中:
import systemd_stopper stopper = systemd_stopper.install() while stopper.run: do_stuff() handle_graceful_shutdown()
函数install()设置信号处理程序并返回一个Stopper对象来查询stop命令的状态。您有多种选择:
# Use other signals for stopping the application. stopper = systemd_stopper.install('USR1', 'HUP') # Wait for a threading.Event instead of polling the run attribute. stopper.event.wait() # returns when the stop signal has been receive # Use a callback function that gets called exactly once, which is useful # for single-threaded IO loops like those of tornado or asyncio ioloop = framework_of_choice.get_io_loop() systemd_stopper.install(callback=ioloop.stop)
安装
pip install systemd-stopper
其他文档
当我有时间写的时候,会添加更多的文档。