作为系统单元运行的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

其他文档

当我有时间写的时候,会添加更多的文档。

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java播放流媒体音乐   LWJGL中的java纹理未显示   java从父集合中删除时删除子对象   mysql希望在我的代码中添加验证,如果表不存在,它应该用java创建新表   java我可以关闭客户端的socket而不引起服务器端的EOFEException吗?   java Primefaces对话框框架咆哮和showMessageInDialog不工作   hadoop配置单元无法初始化类java。网网络接口   关键字中缺少oracle11g Java iBatis   java在RESTAPI中创建PUT和POST端点,而不创建GET端点?   java Math abs和ceil输出编译错误   java Tomcat 8.017代md5及其摘要。球棒   java SpringBean配置xml文件在IteliJ Idea中加载   java为什么在使用Powershell指定Xms和Xmx时,它们什么都不做,但通过Netbeans IDE可以正常工作?   java Drools项目构建失败,kjar打包从7.7版开始