作为系统单元运行的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如何使用JNA创建同一库的多个实例?   java在将Graphql查询作为JSON字符串传递时收到意外的令牌错误   OAuth2 oltu的java问题   java桌面应用程序使用的好的嵌入式数据库是什么?   java Firebase数据库高级查询选项   java正在使磁盘上的EhCache元素过期   java 安卓还原处于backstack中的片段的实例状态   XMemcached中的java异步集   java TimescaleDB是否使用与Postgresql完全相同的JDBC驱动程序?   java从网站c读取信息#   检查java Android中的字符串是否只包含数字和空格   c#如何向web服务发送特殊字符?   grails无法调用需要java的方法。lang.类参数?   java我在组合框中调用的方法不会运行所有代码,它只运行部分代码   java发送带有标头的HTTP GET请求