How to set time limit on raw_input

前端 未结 6 1587
抹茶落季
抹茶落季 2020-11-22 05:52

in python, is there a way to, while waiting for a user input, count time so that after, say 30 seconds, the raw_input() function is automatically skipped?

6条回答
  •  萌比男神i
    2020-11-22 06:27

    from threading import Timer
    
    
    def input_with_timeout(x):    
    
    def time_up():
        answer= None
        print('time up...')
    
    t = Timer(x,time_up) # x is amount of time in seconds
    t.start()
    try:
        answer = input("enter answer : ")
    except Exception:
        print('pass\n')
        answer = None
    
    if answer != True:   # it means if variable have somthing 
        t.cancel()       # time_up will not execute(so, no skip)
    
    input_with_timeout(5) # try this for five seconds
    

    As it is self defined... run it in command line prompt , I hope you will get the answer read this python doc you will be crystal clear what just happened in this code!!

提交回复
热议问题