-1

I have this code:

while True:
    i=input'enter #enter or character:'
    if not i:
        break

This breaks the program if they enter enter, but I want it to break immediately if they don't answer after 3 seconds.

How would I do this?

asdfghjkl
  • 1
  • 3

1 Answers1

1

Python 3 Timed Input (@mediocrity : maybe you vote his answer up if you like the result, since he had to put effort in answering the question and deserves credit) shows a nice example of what you are looking for.

I copied it here for you:

import time
from threading import Thread

answer = None

def check():
    time.sleep(3)
    if answer != None:
        return
    print "Too Slow"

Thread(target = check).start()

answer = raw_input("Input something: ")

print(answer)

print ("done")

I think the minor differences of this answer and your question you can yourself.

I hope that helps

EDIT: I found something really cool for Linux (I do not know if it runs with Windows) here: http://www.garyrobinson.net/2009/10/non-blocking-raw_input-for-python.html

I know it is not yet what you need, but I still post it, because it might help someone else. That is what Gary Robinson wrote:

OCTOBER 17, 2009 Non-Blocking Raw_input For Python [Edited Aug. 30, 2010 to fix a typo in the function name and generally improve formatting]

I needed a way to allow a raw_input() call to time out. In case it's useful to anyone, I wrote this solution which works under Unix-like OS's.

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 ''

ans = None
ans = nonBlockingRawInput("Input Something: ", 3)

print ans