用户输入的Python暂停循环

时间:2019-06-30 01:35:38

标签: python loops

嘿,我试图让循环从用户输入中暂停,例如在终端中有一个输入框,如果您键入pause,它将暂停循环,然后如果您键入start,它将重新开始。

类似这样的事情,但是不断发生“ #Do something”而没有等待输入被发送。

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

2 个答案:

答案 0 :(得分:4)

好,我现在明白了,这是线程的解决方案:

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

答案 1 :(得分:1)

您不能直接使用,因为input会阻止所有内容,直到返回为止。
不过,_thread模块可以帮助您:

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