1

Is it possible to time out python 3 input? I managed to do what I want in Java, but how can you do it in python? Can you use jython and manage to compile it so that it doesn't need a jython installation to run (I only have python available on the target computer)?

import java.io.IOException;

public class TimedRead {
    public static String timedRead(int timeout) {
        long startTime = System.currentTimeMillis();
        long endTime = 0;
        char last = '0';
        String data = "";
        while(last != '\n' && (endTime = System.currentTimeMillis()) - startTime < timeout) {
            try {
                if(System.in.available() > 0) {
                    last = (char) System.in.read();
                    data += last;
                }
            } catch (IOException e) {
                e.printStackTrace();
                return "IO ERROR";
            }
        }
        if(endTime - startTime >= timeout) {
            return null;
        } else {
            return data;
        }
    }
    public static void main(String[] args) {
        String data = timedRead(3000);
        System.out.println(data);
    }
}

Thanks.

EDIT:

I was able to throw an error to cause the thread to halt.

import signal

#This is an "Error" thrown when it times out
class Timeout(IOError):
    pass

def readLine(timeout):
    def handler(signum, frame):
        #Cause an error
        raise Timeout()

    try:
        #Set the alarm
        signal.signal(signal.SIGALRM, handler)
        signal.alarm(timeout)

        #Wait for input
        line = input()

        #If typed before timed out, disable alarm
        signal.alarm(0)
    except Timeout:
        line = None

    return line

#Use readLine like you would input, but make sure to include one parameter - the time to wait in seconds.
print(readLine(3))
Noah Singer
  • 526
  • 2
  • 6
  • 17
  • I don't know any Java and am a bit confused what you want to do. I apologize if this is unhelpful but I recently read something that might help out on this: https://stackoverflow.com/questions/1335507/keyboard-input-with-timeout Hope it's helpful and apologize of it's not. – NerdOfDoom Aug 19 '20 at 23:12

1 Answers1

-1

I'd post this as a comment if I could... Look into the datetime module, http://docs.python.org/3/library/datetime.html - You can use datetime.now() and timedelta to accomplish the same thing as you have above.

John Brodie
  • 5,909
  • 1
  • 19
  • 29