我编写了一个简单的python程序,并将其作为systemd服务启动。在systemd关闭这个正在运行的python程序之前,我想做一些事情(例如,将消息写入日志文件)。在
我尝试了atexit
(就像这篇文章中提到的:Doing something before program exit),我也试图捕捉{
我用的是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
的片段:
在服务文件中,在“
ExecStart=<your python script>
”之后使用systemd服务文件选项“ExecStopPost=<post execution command>
”。在此“ExecStopPost=”选项只应用于某些小型或小型任务。在
相关问题 更多 >
编程相关推荐