How to set time limit on raw_input
The signal.alarm function, on which @jer's recommended solution is based, is unfortunately Unix-only. If you need a cross-platform or Windows-specific solution, you can base it on threading.Timer instead, using thread.interrupt_main to send a KeyboardInterrupt
to the main thread from the timer thread. I.e.:
import thread
import threading
def raw_input_with_timeout(prompt, timeout=30.0):
print(prompt, end=' ')
timer = threading.Timer(timeout, thread.interrupt_main)
astring = None
try:
timer.start()
astring = input(prompt)
except KeyboardInterrupt:
pass
timer.cancel()
return astring
this will return None whether the 30 seconds time out or the user explicitly decides to hit control-C to give up on inputting anything, but it seems OK to treat the two cases in the same way (if you need to distinguish, you could use for the timer a function of your own that, before interrupting the main thread, records somewhere the fact that a timeout has happened, and in your handler for KeyboardInterrupt
access that "somewhere" to discriminate which of the two cases occurred).
Edit: I could have sworn this was working but I must have been wrong -- the code above omits the obviously-needed timer.start()
, and even with it I can't make it work any more. select.select
would be the obvious other thing to try but it won't work on a "normal file" (including stdin) in Windows -- in Unix it works on all files, in Windows, only on sockets.
So I don't know how to do a cross-platform "raw input with timeout". A windows-specific one can be constructed with a tight loop polling msvcrt.kbhit, performing a msvcrt.getche
(and checking if it's a return to indicate the output's done, in which case it breaks out of the loop, otherwise accumulates and keeps waiting) and checking the time to time out if needed. I cannot test because I have no Windows machine (they're all Macs and Linux ones), but here the untested code I would suggest:
import msvcrt
import time
def raw_input_with_timeout(prompt, timeout=30.0):
print(prompt, end=' ')
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) # just to yield to other processes/threads
else:
if time.time() > finishat:
return None
The OP in a comment says he does not want to return None
upon timeout, but what's the alternative? Raising an exception? Returning a different default value? Whatever alternative he wants he can clearly put it in place of my return None
;-).
If you don't want to time out just because the user is typing slowly (as opposed to, not typing at all!-), you could recompute finishat after every successful character input.
Time-Limited Input?
Interesting problem, this seems to work:
import time
from threading import Thread
answer = None
def check():
time.sleep(2)
if answer != None:
return
print("Too Slow")
Thread(target = check).start()
answer = input("Input something: ")
Limit raw_input length
The function getstr()
which is the raw_input
alternative for curses
, works with a character constraint:
s = stdscr.getstr(0,0, 15) #Input is limited to 15 characters, once the limit is hit, it stops accepting more
Limiting raw_input in python
A simple solution will be adding a significant message and then using slicing to get the first 40 characters:
some_var = raw_input("Input (no longer than 40 characters): ")[:40]
Another would be to check if the input length is valid or not:
some_var = raw_input("Input (no longer than 40 characters): ")
if len(some_var) < 40:
# ...
Which should you choose? It depends in your implementation, if you want to accept the input but "truncate" it, use the first approach. If you want to validate first (if input has the correct length) use the second approach.
Related Topics
How to Make a Timezone Aware Datetime Object
How to Invoke the Super Constructor in Python
Find the Column Name Which Has the Maximum Value for Each Row
How Are Tuples Unpacked in for Loops
Pip Install from Pypi Works, But from Testpypi Fails (Cannot Find Requirements)
How to Create a Trie in Python
How to Keep Python Print from Adding Newlines or Spaces
How to Get an Absolute File Path in Python
Else Clause on Python While Statement
Iterate Through Pairs of Items in a Python List
How to Use 'Return' to Get Back Multiple Values from a for Loop? How to Put Them in a List
Python - Pip Install Trouble Shooting - Permissionerror: [Winerror 5] Access Is Denied