【问题标题】:Timing Out Python InputPython 输入超时
【发布时间】:2013-01-05 03:06:37
【问题描述】:

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

【问题讨论】:

标签: python input timeout jython


【解决方案1】:

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

【讨论】:

  • 问题是没有“available()”函数,所以当你调用read()时它似乎锁定了标准输入。
猜你喜欢
  • 1970-01-01
  • 2018-07-27
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
相关资源
最近更新 更多