How to set time limit on raw_input

前端 未结 6 1532
抹茶落季
抹茶落季 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条回答
  •  不思量自难忘°
    2020-11-22 06:36

    I found a solution to this problem in a blog post. Here's the code from that blog post:

    import signal
    
    class AlarmException(Exception):
        pass
    
    def alarmHandler(signum, frame):
        raise AlarmException
    
    def nonBlockingRawInput(prompt='', timeout=20):
        signal.signal(signal.SIGALRM, alarmHandler)
        signal.alarm(timeout)
        try:
            text = raw_input(prompt)
            signal.alarm(0)
            return text
        except AlarmException:
            print '\nPrompt timeout. Continuing...'
        signal.signal(signal.SIGALRM, signal.SIG_IGN)
        return ''
    

    Please note: this code will only work on *nix OSs.

提交回复
热议问题