سؤال

Using code I found here to implement a simple daemon, I'm wondering if there is any way for me to get the daemon to perform an action just before being stopped. The idea is that in my script, I'm using a serial connection to an external device, and I would like to close it cleanly before shutting down the daemon.

During the init loop of the App() Class, I'm doing all the preparation and preliminary setup. Then, the run function takes care of starting the serial connection, discarding the first few values and starting the main loop (that just retrieves the value from the serial connection, and saves them to an external server).

Now, what I'd like to do is to add some just-before-exit action, like closing the serial connection, and getting a little summary of the data sent to the log file.

Is there an easy way to do that? (Or even a hard one for that matters).

For the record, I've also thought of using this way of creating a daemon, which could be an easier way to do what I try to do.

Here is what my code looks like for now:

#standard libraries from python
import logging, sys, time

#3rd party lib
import serial, requests
from daemon import runner

class App():
    def __init__(self):
        #some initialize also including the ones from the example
        serialport = '/dev/ttyACM0'

    def run(self):
        #Serial start
        ser = serial.Serial()
        ser.port = serialport
        ser.open()

        #First values discarded
        for i in range(30):
            ser.readline()[:-1]
        #Yes, that's ugly!
        i = 1

        #Main loop
        while True:
            # Serial retrieve
            values = ser.readline()
            r = requests.get(url, params=values)
            logger.info("%s values sent", str(i))
            values = ''
            i += 1
            time.sleep(3)

app = App()
#daemon starting stuff from example

Thanks for the help!

هل كانت مفيدة؟

المحلول

This is covered in the stdlib atexit. On a more granular level for having code that executes before an object is deleted, you can implement a del method.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top