Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pause loop on user input

Hey I am trying to have a loop be pausable from user input like having a input box in the terminal that if you type pause it will pause the loop and then if you type start it will start again.

while True:
    #Do something
    pause = input('Pause or play:')
    if pause == 'Pause':
        #Paused

Something like this but having the #Do something continually happening without waiting for the input to be sent.

like image 291
Gus Avatar asked Apr 12 '26 01:04

Gus


1 Answers

Ok I get it now, here is a solution with Threads:

from threading import Thread
import time
paused = "play"
def loop():
  global paused
  while not (paused == "pause"):
    print("do some")
    time.sleep(3)

def interrupt():
  global paused
  paused = input('pause or play:')


if __name__ == "__main__":
  thread2 = Thread(target = interrupt, args = [])
  thread = Thread(target = loop, args = [])
  thread.start()
  thread2.start()
like image 90
A Monad is a Monoid Avatar answered Apr 14 '26 13:04

A Monad is a Monoid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!