Python 暂停循环以等待用户输入

3

嗨,我正在尝试让循环可以通过用户输入来暂停,就像在终端中有一个输入框,如果您输入 pause,它将暂停循环,然后如果您输入 start,它将重新开始。

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

与此类似,但是 #执行某些操作 会持续发生,而不需要等待输入被发送。


1
你打算如何中断“暂停”? - David Zemens
3
我强烈怀疑你没有清楚地说明你想要达到的目标。无论如何,这是一个猜测,请看Python中的非阻塞raw_input() - martineau
1
@DavidZemens 你说得对,你不能在同一个线程中完成它!所以我创建了两个线程,一个用于循环,另一个用于中断。 - developer_hatch
@martineau 那将是另一个很棒的方法!感谢分享。 - developer_hatch
2个回答

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
你无法直接实现,因为 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())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接