是否有可能超时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))
如果可以的话,我会把这篇文章作为评论发表。查看datetime模块,http://docs.python.org/3/library/datetime.html -您可以使用datetime.now()和timedelta来完成与上面相同的事情。