python - How to set time limit on raw_input -


in python, there way to, while waiting user input, count time after, 30 seconds, raw_input() function automatically skipped?

the signal.alarm function, on @jer's recommended solution based, unfortunately unix-only. if need cross-platform or windows-specific solution, can base on threading.timer instead, using thread.interrupt_main send keyboardinterrupt main thread timer thread. i.e.:

import thread import threading  def raw_input_with_timeout(prompt, timeout=30.0):     print prompt,         timer = threading.timer(timeout, thread.interrupt_main)     astring = none     try:         timer.start()         astring = raw_input(prompt)     except keyboardinterrupt:         pass     timer.cancel()     return astring 

this return none whether 30 seconds time out or user explicitly decides hit control-c give on inputting anything, seems ok treat 2 cases in same way (if need distinguish, use timer function of own that, before interrupting main thread, records somewhere fact timeout has happened, , in handler keyboardinterrupt access "somewhere" discriminate of 2 cases occurred).

edit: have sworn working must have been wrong -- code above omits obviously-needed timer.start(), and can't make work more. select.select obvious other thing try won't work on "normal file" (including stdin) in windows -- in unix works on files, in windows, on sockets.

so don't know how cross-platform "raw input timeout". windows-specific 1 can constructed tight loop polling msvcrt.kbhit, performing msvcrt.getche (and checking if it's return indicate output's done, in case breaks out of loop, otherwise accumulates , keeps waiting) , checking time time out if needed. cannot test because have no windows machine (they're macs , linux ones), here untested code suggest:

import msvcrt import time  def raw_input_with_timeout(prompt, timeout=30.0):     print prompt,         finishat = time.time() + timeout     result = []     while true:         if msvcrt.kbhit():             result.append(msvcrt.getche())             if result[-1] == '\r':   # or \n, whatever win returns;-)                 return ''.join(result)             time.sleep(0.1)          # yield other processes/threads         else:             if time.time() > finishat:                 return none 

the op in comment says not want return none upon timeout, what's alternative? raising exception? returning different default value? whatever alternative wants can put in place of return none;-).

if don't want time out because user typing slowly (as opposed to, not typing @ all!-), recompute finishat after every successful character input.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -