pythonpython-watchdog

Python: while True vs input() when using watchdog


I'm using python watchdog library to catch errors in logs of non-python CRM and I need to reduce the load as much as possible. Watchdog's Observer don't keep terminal attached so you need to make program running endlessly. So, I found two ways to do it:

def first_way(observer: PollingObserver):
    try:
        while True:
            time.sleep(100)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()


def second_way(observer: PollingObserver):
    input("Press <enter> to stop")
    observer.stop()

Both of them work. If I get it right, input() just pause program execution, so I think the second way is better... But it looks too easy to be true.

So I'd like to hear the pros and cons (or suggestion with alternative option)

I settled on input(), but I still have doubts


Solution

  • Using the Python Watchdog library to monitor log files for errors in a non-Python CRM system is a creative approach. Your focus on minimizing resource usage while ensuring the program runs continuously is crucial, especially in a production environment. Let's compare the two methods you've mentioned for keeping the program running:

    First Way: Using time.sleep in a Loop

    Pros:

    Cons:

    Second Way: Using input()

    Pros:

    Cons:

    Alternative: Using a Signal Handler

    If you're looking for a method that combines the benefits of both approaches (minimal resource usage and the ability to stop the program gracefully without requiring an active terminal session), consider using signal handling. This approach allows your program to catch system signals (like SIGINT for a keyboard interrupt or SIGTERM for a termination request) and stop gracefully.

    import signal
    import time
    
    def signal_handler(signum, frame):
        print('Signal received, stopping observer.')
        observer.stop()
        observer.join()
        exit(0)
    
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    # Start your observer here
    observer.start()
    
    while True:
        time.sleep(100)
    

    Pros:

    Cons:

    In summary, the best approach depends on your specific deployment scenario and requirements. If you need the program to run in the background with minimal interaction, using a signal handler might be the most flexible and resource-efficient method.