【发布时间】:2018-07-07 09:52:18
【问题描述】:
我正在开发一个小项目,其中的脚本用于监控用户的键盘输入,我只希望脚本运行 1 分钟。在那一分钟过去后,我想要输入的最终打印语句并终止脚本。 time.sleep 函数在这里不是一个可行的选择,因为我想更新变量并接收每个动作的输出,而使用 sleep 只会延迟每个输入。
from pynput import keyboard
word_counter = 0
def on_press(key):
global word_counter
try:
print('alphabet key {} pressed'.format(key.char))
except AttributeError:
if key == keyboard.Key.space:
word_counter += 1
print(word_counter)
elif key == keyboard.Key.esc:
return False
print('special key {} pressed'.format(key))
with keyboard.Listener(on_press=on_press) as listener:
listener.join()
# After a minute, this will be the final output and the program will terminate
print('You typed a total of {} words in a minute'.format(word_counter))
【问题讨论】:
-
那么,哪个部分应该运行 1 分钟?我不明白这段代码是什么..
-
整个脚本应该运行 1 分钟。该代码基本上只是监视我的输入。一段时间后,我想终止整个程序。
-
您可能会在这里找到答案,这可能会帮助您解决问题:stackoverflow.com/questions/2831775/…