嗨,我正在尝试让循环可以通过用户输入来暂停,就像在终端中有一个输入框,如果您输入 pause
,它将暂停循环,然后如果您输入 start,它将重新开始。
while True:
#Do something
pause = input('Pause or play:')
if pause == 'Pause':
#Paused
与此类似,但是 #执行某些操作
会持续发生,而不需要等待输入被发送。
嗨,我正在尝试让循环可以通过用户输入来暂停,就像在终端中有一个输入框,如果您输入 pause
,它将暂停循环,然后如果您输入 start,它将重新开始。
while True:
#Do something
pause = input('Pause or play:')
if pause == 'Pause':
#Paused
与此类似,但是 #执行某些操作
会持续发生,而不需要等待输入被发送。
好的,现在我明白了,这里有一个使用线程的解决方案:
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()
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())