import time
i = 0
while True:
i += 1
time.sleep(0.2)
print("i's value is " + str(i))
input()
这是我的代码。所以从根本上说,我想让它永远计数,当我输入一些东西是stops breaks,但是它要求每个循环都有一个输入。这有可能吗?
发布于 2019-02-21 04:30:20
您需要将代码拆分为两个线程,一个线程持续打印,另一个线程侦听输入。当输入侦听器接收到输入时,它将需要向打印线程发送一条消息以停止。
import time
import threading
# Create printer function to print output
# make sure you add a lock so the printing doesn't go all funny
def printer(lock):
i = 0
while True:
i += 1
time.sleep(0.2)
with lock:
print(f"i's value is {i}")
# create a thread lock to allow for printing
lock = threading.Lock()
# Create the thread to print
p = threading.Thread(target=printer, args=(lock,), daemon=True)
# start the thread
p.start()
# wait for input and when received stop the thread.
if input():
p.join()
https://stackoverflow.com/questions/54788237
复制相似问题