【问题标题】:In python, how do I end the countdown when I have input在python中,当我输入时如何结束倒计时
【发布时间】:2020-03-26 16:20:02
【问题描述】:

说明:现在,我已经做了输入和倒计时,两者是同时进行的,但是我想这样实现:

(1)当我在倒计时不输入任何内容时,它会在倒计时后执行另一个函数

(2)当我在倒计时结束前输入一些东西时,倒计时会暂停,然后会执行另一个函数

我的代码如下:

import time
from threading import Thread


def waitinput():

    wait_input_str = input("Please enter your account:\n")
    print(wait_input_str)


thd = Thread(target=waitinput)
thd.daemon = True
thd.start()
for i in reversed(range(1, 11)):
    print("\rcountdown:{}second".format(i), end="")
    time.sleep(1)
# ###########################################

谁知道,请回复我 谢谢!

【问题讨论】:

    标签: python multithreading input timeout


    【解决方案1】:

    您可以使用isAlive() 方法检查您的线程是否已终止。

    在你的情况下:

    import time
    from threading import Thread
    
    
    def waitinput():
    
        wait_input_str = input("Please enter your account:\n")
        print(wait_input_str)
    
    
    thd = Thread(target=waitinput)
    thd.daemon = True
    thd.start()
    for i in reversed(range(1, 11)):
        if not thd.isAlive():
            # Execute 2
            print("\nCountdown has stopped")
            break
        print("\rcountdown:{}second".format(i), end="")
        time.sleep(1)
    
    if thd.isAlive():
        # Execute 1
        print("\nCountdown has ended")
    

    【讨论】:

      猜你喜欢
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多