定时输出Python

时间:2013-01-05 03:06:37

标签: python input timeout jython

是否可以超时python 3输入?我设法在Java中做我想做的事,但你怎么能在python中做到这一点?你可以使用jython并设法编译它,以便它不需要运行jython安装(我只在目标计算机上有python)吗?

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);
    }
}

感谢。

编辑:

我能够抛出错误导致线程停止。

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

1 个答案:

答案 0 :(得分:-1)

如果可以,我会发布此评论作为评论...查看datetime模块,http://docs.python.org/3/library/datetime.html - 您可以使用datetime.now()和timedelta来完成与上面相同的操作。< / p>