1

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

1 に答える 1

-1

できればこれをコメントとして投稿します... datetime モジュールを調べてくださいhttp://docs.python.org/3/library/datetime.html - datetime.now() と timedelta を使用して達成できますあなたが上に持っているのと同じこと。

于 2013-01-05T03:12:40.127 に答える