首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何让input()在python 3中不会停止

如何让input()在python 3中不会停止
EN

Stack Overflow用户
提问于 2019-02-20 22:05:43
回答 1查看 1.1K关注 0票数 0
import time

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

这是我的代码。所以从根本上说,我想让它永远计数,当我输入一些东西是stops breaks,但是它要求每个循环都有一个输入。这有可能吗?

EN

回答 1

Stack Overflow用户

发布于 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()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54788237

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档