我正在寻找一个Python脚本,它在每个时间间隔内都会持续等待用户输入一段时间.如果用户未能在此时间范围内提供输入,脚本应自动执行预定义的操作并无限期地继续此过程.换句话说,我需要一个 routine ,它永远运行,但快速判断用户输入的任何字符.
为了实现这一点,我制作了一个代码片段,其中getch
函数捕获用户输入的字符.程序在超时时间内等待用户的输入.如果用户未能在此时间间隔内提供输入,则会发出通知以指示时间已过.
import threading
def getch(input_str: list) -> None:
"""Gets a single character"""
try:
import msvcrt
input_str.append(msvcrt.getch().decode("utf-8"))
except ImportError:
import sys
import termios
import tty
fd = sys.stdin.fileno()
oldsettings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, oldsettings)
input_str.append(ch)
def input_with_timeout(timeout):
print("You have {} seconds to enter something:".format(timeout))
input_str = []
input_thread = threading.Thread(target=getch, args=(input_str,))
input_thread.start()
input_thread.join(timeout)
if input_thread.is_alive():
print("Time's up! Performing default operation.")
else:
print("You entered:", input_str)
while True:
input_with_timeout(5)
当用户在分配的时间内提供输入时,系统正常工作.然而,如果时间过go 了,就会出现两个问题:第一,文本显示出现故障,导致文本放错位置;第二,用户必须多次输入他们的响应,因为一次try 似乎不能准确地记录输入.
Because libraries such as pynput and keyboard have limitations in some environments, I cannot use them.