How can I stop the 'input()' function after a certain amount of time?

后端 未结 2 704
一个人的身影
一个人的身影 2021-01-28 12:13

I\'m trying to figure out how to make python stop accepting input after a certain amount of time.

What I\'ve got so far works, but won\'t stop the program until the user

相关标签:
2条回答
  • 2021-01-28 12:51

    just use time.sleep() The sleep method causes a python program to freeze for certain amount of time (in milliseconds). So, if you want to stop input() for a certain amount of time then you can do it this way,

    from time import sleep
    sleep(1000) #stops the program for 1 seconds
    s = input()
    

    sauce

    0 讨论(0)
  • 2021-01-28 12:55

    You could use Multi-threading for this.

    from threading import Thread
    import time
    import os
    
    answer = None
    
    
    def ask():
        global start_time, answer
        start_time = time.time()
        answer = input("Enter a number:\n")
        time.sleep(0.001)
    
    
    def timing():
        time_limit = 5
        while True:
            time_taken = time.time() - start_time
            if answer is not None:
                print(f"You took {time_taken} seconds to enter a number.")
                os._exit(1)
            if time_taken > time_limit:
                print("Time's up !!! \n"
                      f"You took {time_taken} seconds.")
                os._exit(1)
            time.sleep(0.001)
    
    
    t1 = Thread(target=ask)
    t2 = Thread(target=timing)
    t1.start()
    t2.start()
    
    0 讨论(0)
提交回复
热议问题