我正在一个小项目中,该脚本用于监视用户的键盘输入,并且我只希望脚本运行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))
答案 0 :(得分:5)
这将是答案:
from pynput import keyboard
import threading, time
word_counter = 0
def background():
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()
def wait():
time.sleep(60)
background = threading.Thread(name = 'background', target = background)
background.start()
wait()
# 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)
from pynput import keyboard
import time
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))
i=int(time.time())+60
while(time.time()<=i):
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分钟。
例如:
import time
i=int(time.time())+60
print("ddnd")
while(int(time.time())<=i):
print("dlksnd")