gpt4 book ai didi

python - 缩短用户输入的 sleep 时间

转载 作者:行者123 更新时间:2023-12-03 15:07:06 25 4
gpt4 key购买 nike

我试图找到一种方法来缩短 time.sleep(600)如果用户输入一个键,而不诉诸于一些丑陋的黑客,如:

key_pressed = False
for i in range(600):
key_pressed = key_was_pressed()
if not key_pressed:
time.sleep(1)
else:
break

最佳答案

这是使用 signal.alarm 的实现的跨平台改编。中断(在 Windows 上不可用的想法)。此代码应该适用于 Linux、macOS 和 Windows。第三方辅助库 readchar 可以用pip install readchar安装.

import os
import signal
import sys

from threading import Timer
from readchar import readkey

def wait_for(key="x", timeout=600):
pid = os.getpid()
sig = signal.CTRL_C_EVENT if os.name == "nt" else signal.SIGINT
timer = Timer(timeout, lambda: os.kill(pid, sig))
print(f"waiting {timeout}s for user to press {key!r} ...")
timer.start() # spawn a worker thread to interrupt us later
while True:
k = readkey()
print(f"received {k!r}")
if k == key:
timer.cancel() # cancel the timer
print("breaking")
break

def main():
import sys
try:
wait_for(key=sys.argv[1], timeout=int(sys.argv[2]))
except KeyboardInterrupt as err:
print("user took too long")

if __name__ == "__main__":
main()

关于python - 缩短用户输入的 sleep 时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61759270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com