I wrote a simple python program and started it as a systemd service. I'd like to do something (e.g. write message to logfile) before systemd closes this running python program.
I tried atexit
(like mentioned in this post: Doing something before program exit), I also tried to catch SIGTERM
(like described here: https://nattster.wordpress.com/2013/06/05/catch-kill-signal-in-python/) but without success .
I am using raspbian-jessie and python2.7.
How can I do something before systemd
kills the running python program?
Here is an example code snippet (with 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))
This is a snippet with 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))