让python脚本运行一分钟 [英] make python script run for a minute

查看:86
本文介绍了让python脚本运行一分钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个小项目,其中脚本用于监视用户的键盘输入,我只希望脚本运行 1 分钟.那一分钟过去后,我想要输入的最终打印语句并终止脚本.time.sleep 函数在这里不是一个可行的选择,因为我想更新变量并接收每个动作的输出,而使用 sleep 只会延迟每个输入.

I'm working on a small project where the script is to monitor user's keyboard inputs and I only want the script to run for a duration of 1 minute. After that minute has passed, I want a final print statement of the inputs and to terminate the script. The time.sleep function is not a viable choice here since I want to update variables and receive output for every action, and using sleep will only delay each input.

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))

推荐答案

这就是答案:

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))

这篇关于让python脚本运行一分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆