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: ")
Timed user input in Python
You can use the Timer
class for this purpose
from threading import Timer
timeout = 10
t = Timer(timeout, print, ['Sorry, times up!'])
t.start()
prompt = "You have %d seconds to answer the question. What color do cherries have?...\n" % timeout
answer = input(prompt)
t.cancel()
Output:
You have 10 seconds to answer the question. What color do cherries have?
(After 10 seconds)
Sorry, times up!
Input Time Limit
import time
at the start of it, then:
...
if whichtasktodo == "Empty Garbage":
start_time = time.time()
...
end_time = time.time()
if (emptygarbagetask = "Swipe Down") and (end_time - start_time <= 5):
...
...
Time limit for an input
import java.util.Timer;
import java.util.TimerTask;
import java.io.*;
public class test
{
private String str = "";
TimerTask task = new TimerTask()
{
public void run()
{
if( str.equals("") )
{
System.out.println( "you input nothing. exit..." );
System.exit( 0 );
}
}
};
public void getInput() throws Exception
{
Timer timer = new Timer();
timer.schedule( task, 10*1000 );
System.out.println( "Input a string within 10 seconds: " );
BufferedReader in = new BufferedReader(
new InputStreamReader( System.in ) );
str = in.readLine();
timer.cancel();
System.out.println( "you have entered: "+ str );
}
public static void main( String[] args )
{
try
{
(new test()).getInput();
}
catch( Exception e )
{
System.out.println( e );
}
System.out.println( "main exit..." );
}
}
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.
Related Topics
Multi Platform Portable Python
How to Install Python 3.6.5 on My Ubuntu 19.10 That Already Contains Python 3.7.5
How to Install Pip on Arch Linux
Passing Extra Arguments Through Connect
Scatter Plots in Pandas/Pyplot: How to Plot by Category
Removing Elements That Have Consecutive Duplicates
How to Run Multiple Python Versions on Windows
How to Add Group Labels for Bar Charts in Matplotlib
Pip Install MySQL-Python Fails with Environmenterror: MySQL_Config Not Found
Create Pandas Dataframe from a String
Problems Adding Path and Calling External Program from Python
Bring the Current Python Program to Background
What Are the Differences Between the Urllib, Urllib2, Urllib3 and Requests Module
What Are the Risks of Running 'Sudo Pip'
Why Does Id({}) == Id({}) and Id([]) == Id([]) in Cpython