[英]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. 嘿,我试图让循环从用户输入中暂停,例如在终端中有一个输入框,如果您键入pause,它将暂停循环,然后如果您键入start,它将再次开始。
Something like this but having the '#Do something' continually happening without waiting for the input to be sent. 诸如此类,但是不断发生“ #Do something”,而无需等待输入被发送。
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. 您不能直接input
,因为input
阻塞所有内容,直到返回为止。
The _thread
module, though, can help you with that: _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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.