Python 缩短用户输入时的睡眠时间
我正试图找到一种方法来缩短Python 缩短用户输入时的睡眠时间,python,Python,我正试图找到一种方法来缩短时间。如果用户输入了一个键,就可以使用sleep(600),而不必求助于一些丑陋的黑客,比如: key_pressed = False for i in range(600): key_pressed = key_was_pressed() if not key_pressed: time.sleep(1) else: break 这是对使用信号.报警中断(在Windows上不可用)实现的跨平台改编。此代码应适用
时间。如果用户输入了一个键,就可以使用sleep(600)
,而不必求助于一些丑陋的黑客,比如:
key_pressed = False
for i in range(600):
key_pressed = key_was_pressed()
if not key_pressed:
time.sleep(1)
else:
break
这是对使用
信号.报警
中断(在Windows上不可用)实现的跨平台改编。此代码应适用于Linux、macOS和Windows。第三方帮助程序库可以通过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()
你考虑过侦听器线程+通知吗?我会接受任何键(CTRL-C除外),但如果我可以设置键,那就更好了。假设Python3安全吗?平台(Win/*nix)是否事先已知?这个项目是偶然使用龙卷风吗?是的,蟒蛇3。Windows,但一般的解决方案总是更好。@d99kris公认的答案是忙着等待,这正是我想要避免的,正如你在我的问题中看到的丑陋的黑客行为。(我知道
time.sleep()
在技术上也在忙着等待,但比while True:
循环的资源密集度要低得多)这不会让while True
循环淹没一个内核吗?不。getch正在阻塞。readchar.readkey()
在Spyder上似乎不起作用,但如果我模拟用户按下x
,它起作用了。但是,如果我什么也不做,它就不起作用了,我会在C:\Users\Francois\Anaconda3\lib\site packages\matplotlib\mpl data\stylelib\u classic\u test\u patch.mplstyle中的第4行得到:重新启动内核坏键“text.kerning\u factor”。您可能需要从获取更新的matplotlibrc文件https://github.com/matplotlib/matplotlib/blob/v3.1.3/matplotlibrc.template 或者从matplotlib源代码发行版
,然后在同一控制台中重试会使其崩溃。@FrançoisM。我对斯派德不熟悉。这段代码在您的平台上直接在Python中工作吗?