在systemd停止运行python servi之前执行一些操作

2024-09-24 02:20:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个简单的python程序,并将其作为systemd服务启动。在systemd关闭这个正在运行的python程序之前,我想做一些事情(例如,将消息写入日志文件)。在

我尝试了atexit(就像这篇文章中提到的:Doing something before program exit),我也试图捕捉{}(如本文所述:https://nattster.wordpress.com/2013/06/05/catch-kill-signal-in-python/),但没有成功。在

我用的是raspbian jessie和python2.7。在

systemd杀死正在运行的python程序之前,我如何做?在

下面是一个示例代码片段(带有atexit):

#!/usr/bin/env python

from pymodbus.server.async import StartTcpServer

from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext

import atexit

import logging
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)

def exit_handler():
    log.warning('My application is ending!')

atexit.register(exit_handler)

store = ModbusSlaveContext(
    di = ModbusSequentialDataBlock(0, [17]*100),
    co = ModbusSequentialDataBlock(0, [17]*100),
    hr = ModbusSequentialDataBlock(0, [17]*100),
    ir = ModbusSequentialDataBlock(0, [17]*100))
context = ModbusServerContext(slaves=store, single=True)

identity = ModbusDeviceIdentification()
identity.VendorName  = 'Pymodbus'
identity.ProductCode = 'PM'
identity.VendorUrl   = 'http://github.com/bashwork/pymodbus/'
identity.ProductName = 'Pymodbus Server'
identity.ModelName   = 'Pymodbus Server'
identity.MajorMinorRevision = '1.0'

StartTcpServer(context, identity=identity, address=("localhost", 5020))

这是一个带有SIGTERM的片段:

^{pr2}$

Tags: fromimport程序comlogloggingexitidentity
1条回答
网友
1楼 · 发布于 2024-09-24 02:20:01

在服务文件中,在“ExecStart=<your python script>”之后使用systemd服务文件选项“ExecStopPost=<post execution command>”。在

此“ExecStopPost=”选项只应用于某些小型或小型任务。在

相关问题 更多 >