Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep python process alive - the right way

I've see this question a lot but I'm not satisfied with the answers. I know server programs like Django and Flask/Werkzeug have startserver/run method that keeps the process alive until a stop signal is received.

I want to implement something similar but I cannot figure out how to do it. I assume that an eternal loop is a bad way to do it because it is wasted processing time. I'd rather not use a third party library.

My program must stay alive to wait for callbacks, communicate with a server, monitor its internal state, etc.

Pseudocode:

import ...

class Main():
    def __init__():
        self.sensors = sensors.register()
        self.database = remote.connect()
        self.running = True

    def start():
    """ this is what I assume is bad """
        while self.running:
            pass

    def stop():
        self.running = False
        self.cleanup()

    def cleanup():
        self.database.disconnect()
        self.sensors.unregister()
like image 211
Anders_K Avatar asked Oct 28 '25 04:10

Anders_K


2 Answers

There is a general paradigm not specific to python to deal with this kind of situation called event loops. If you search for it on the internet, you will find several libraries implementing it. If you use asyncio you do not need third party libraries as it ships with python3. I would advise you to familiarize yourself with the concept, the web is full of examples. See e.g. this tutorial. We get this example from there:

import asyncio

async def work():
    while True:
        await asyncio.sleep(1)
        print("Task Executed")

loop = asyncio.get_event_loop()
try:
    asyncio.ensure_future(work())
    loop.run_forever()
except KeyboardInterrupt:
    pass
finally:
    print("Closing Loop")
    loop.close()

I hope this helps.

like image 182
ilmiacs Avatar answered Oct 29 '25 19:10

ilmiacs


You could:

import time
time.sleep(x) #seconds

And only check status at the desired interval.

For network events you could use sockets. https://python-socketio.readthedocs.io/en/latest/

like image 21
dVeza Avatar answered Oct 29 '25 17:10

dVeza