如何使input()不因python 3而停止

时间:2019-02-20 14:05:43

标签: python python-3.x input counter

import time

i = 0
while True:
    i += 1
    time.sleep(0.2)
    print("i's value is " + str(i))
    input()

这是我的代码。所以从根本上讲,我想让它永远计数,当我键入某些内容时,stops -breaks-代替了,但是它要求为每个循环输入一个值。这有可能吗?

1 个答案:

答案 0 :(得分:0)

您需要将代码分成两个线程,一个线程连续打印,另一个线程监听输入。当输入侦听器收到输入时,它将需要向打印线程发送一条消息以停止。

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