如何使程序在5秒内终止或识别键盘输入



如何使程序在5秒内终止或识别键盘输入,在本例中:

vb = input("Press Enter to Close the Windown Or wait 5 seconds and the window will close automaticallynn")

您可以为此目的使用inputimeout包装。

在提示中:输入显示消息

in timeout:以秒为单位的超时

from inputimeout import inputimeout
....
Your exiting code
....
....
vb = inputimeout(prompt='Press Enter to Close the Windown Or wait 5 seconds and the window will close automaticallynn', timeout=5)

这里有一种使用信号的方法:

import signal
import time
def handler(s, f):
raise Exception("timeout")

signal.signal(signal.SIGALRM, handler)
signal.alarm(5)
try:
vb = input("Press enter or wait ")
signal.alarm(0)
except Exception as e:
pass