让python脚本运行一分钟

use*_*311 2 python scripting time

我正在开发一个小项目,其中脚本是监视用户的键盘输入,我只希望脚本运行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))
Run Code Online (Sandbox Code Playgroud)

Hos*_*eon 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))
Run Code Online (Sandbox Code Playgroud)