在 systemd 停止运行 python 服务之前做一些事情

wew*_*ewa 5 python debian exit python-2.7 systemd

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

我尝试过atexit(就像这篇文章中提到的:在程序退出之前做一些事情),我也尝试捕获SIGTERM(就像这里描述的: 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))
Run Code Online (Sandbox Code Playgroud)

这是一个片段SIGTERM

#!/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 signal
import sys

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

def signal_term_handler(signal, frame):
    log.warning('got SIGTERM')
    sys.exit(0)

signal.signal(signal.SIGTERM, signal_term_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))
Run Code Online (Sandbox Code Playgroud)

Sat*_*urn 1

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

此“ExecStopPost=”选项只能用于某些小型或次要任务。