我所拥有的
import time
r = 0
while True:
print(r)
r += 1
time.sleep(3)
number = input()
num = int(number)
#????????????
if num == r:
print('yes')
else:
print('no')
我想做的是使它在打印每个数字后有一个3秒钟的窗口供用户输入r的值,如果用户不执行任何操作,则使程序继续运行。我该怎么办?
答案 0 :(得分:2)
这是使用signal
和Python 3.6+
的有效代码,该代码应在任何Unix & Unix-like
系统下运行,并且在Windows
下将失败:
import time
import signal
def handler_exception(signum, frame):
# Raise an exception if timeout
raise TimeoutError
def input_with_timeout(timeout=5):
# Set the signal handler
signal.signal(signal.SIGALRM, handler_exception)
# Set the alarm based on timeout
signal.alarm(timeout)
try:
number = input(f"You can edit your number during {timeout}s time: ")
return int(number)
finally:
signal.alarm(0)
r = 1
while True:
number = input("Enter your number: ")
num = int(number)
try:
num = input_with_timeout()
# Catch the exception
# print a message and continue the rest of the program
except TimeoutError:
print('\n[Timeout!]')
if num == r:
print('yes')
else:
print('no')
演示1:无超时执行
Enter your number: 2
You can edit your number during 5s time: 1
yes
Enter your number:
演示2:执行超时
Enter your number: 2
You can edit your number during 5s time:
[Timeout!]
no
Enter your number: