首页 > 解决方案 > Python 没有按应有的方式运行某些代码行

问题描述

有人可以帮我处理这段代码吗?它的用途是进行 2 秒的定时输入,即使用户在控制台中输入或未输入某些内容(当时),它也需要打印最后一行。当我不输入任何内容时,在打印“太慢”后它会要求我输入相同的输入,所以我添加了 IF,但它并没有真正注意到它。我希望有人能帮助我。谢谢!

import time
from threading import Thread
i = 0
answer = None

def check():
    time.sleep(2)
    if answer != None:
        return
    print("Too Slow") #prints this if nothing is typed in (for 2 seconds)
if i == 0:
  i = 1
  Thread(target = check).start()
  answer = input("Input something: ") #program doesn't even notice IF and asks me the second time for input

print("This should be printed instantly after printing Too Slow (when user doesn't input anything)")

标签: python

解决方案


return函数中的仅check导致线程完成,但调用独立于该线程,因此在函数完成input时不会中断。有关使用信号模块的替代解决方案,check请参阅此答案。


推荐阅读