Search code examples
pythonpython-3.xmultithreadingwatchdog

Python -i flag for production


I have a Python program that uses a watchdog, the watchdog is running on a separate thread. In the main thread, I have no code, so in order to keep the program running I'm using a while true sleep.

Should I use the -i flag instead to make the program stall?

Is it good for production?


Solution

  • Per the official documentation, a while-sleep loop is the idiomatic way of working with the library (as they don't offer running on the main thread).

    They give the following usage example:

    observer = Observer()
    observer.schedule(event_handler, ".", recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    finally:
        observer.stop()
        observer.join()
    

    -i or interactive Python mode is not meant to be used as a blocking mechanism. Moreover, I fear that sending a sigint (Ctrl-C) will not actually exit the Python program in a clean fashion as the interactive interpreter catches those signals and eventually prints the KeyboardInterrupt exception without terminating.

    If all the program does is hosting the watchdog, the while loop is probably a good solution. Otherwise, a signal handler can be registered, which triggers an event. The main thread can wait on this event or do other operations and eventually choose to terminate based on the event. I can add some example code if you wish. It will prevent the "useless" while loop.