简体   繁体   中英

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.

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

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

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()

You can't directly, as input blocks everything until it returns.
The _thread module, though, can help you with that:

import _thread

def input_thread(checker):
    while True:
        text = input()
        if text == 'Pause':
            checker.append(True)
            break
        else:
            print('Unknown input: "{}"'.format(text))

def do_stuff():
    checker = []
    _thread.start_new_thread(input_thread, (checker,))
    counter = 0
    while not checker:
        counter += 1
    return counter

print(do_stuff())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM