Merig
Merig

Reputation: 2011

End loop with user input in Python

I have a this update function:

def update(self, interval=60):
    while True:
        # Do stuff

        time.sleep(interval)

I would like to know the possible ways to, once the function is called, interrupt the loop via user input while leaving the script running.

All I found were answer from 5+ years ago, mostly platform-dependant.Is there any new/reliable way to achieve this? I would rather avoid threading, if possible. Using 3.7

Upvotes: 0

Views: 66

Answers (1)

jhill515
jhill515

Reputation: 943

You could create an interrupt handler with signal. This, however, still relies on the system thread for monitoring; I don't think it's costly since the thread is already spawned.

In essence, you'd still need a sort of global flag that governs the loop. When the interrupt trigger happens (user input, etc.), the interrupt changes the value of the flag, and the loop terminates allowing for other processing.

Upvotes: 1

Related Questions