0

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

3
  • Ctrl + c will kill the loop. Theres not enough info on the specifics here. If the code just has an except then you'll have to kill the process. except Exception will allow KeyboardInterrupt Commented Mar 8, 2019 at 17:35
  • 1
    Threading is certainly the more reliable way, since it doesn't rely on the main loop handing the control to the input checking routine, which may not necessarily happen in a timely manner if the main loop is blocked or waiting for a timeout on some resource. Commented Mar 8, 2019 at 17:38
  • Without threading your time.sleep is a 60 second hang in the program. Commented Mar 8, 2019 at 17:40

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.