在功能运行时检查按键

时间:2021-01-30 09:48:11

标签: python keyboard keypress

我有这个功能可以运行大约一个小时左右。 我需要一种在 store_data() 函数运行时不断检查按键的方法。当前的代码给了我一个非常小的时间框架来按下组合。有没有办法继续检查按键? for 循环持续了一两个小时,我需要在执行函数时不断检查按键。我可以使用 ctrl + c,但我不想要那样。我想在按下某个组合键时引发键盘中断错误。谢谢

import keyboard
import time

def store_data():
        dict_of_data = []
        excel_file = read_excel()
        for word in excel_file:
            try:
                if keyboard.is_pressed('ctrl + alt + o'):
                    print("pressed")
                    raise KeyboardInterrupt("key interrupted")
                word_data = another_func(word)
                time.sleep(1)
            except KeyboardInterrupt:
                open_excel() #another func that i need to call if "ctrl + alt + o" is pressed and pause the current function
                word_data = another_func(symbol)
                pass
            dict_of_data.append(word_data)

        return dict_of_data

1 个答案:

答案 0 :(得分:0)

热键似乎解决了这个问题。另外,我不必引发 KeyboardInterrupt 错误。此处的代码似乎运行良好。

def func_called():
    print("worked")
    another_func()
    pass


def store_data():
    dict_of_data = []
    excel_file = read_excel()
    keyboard.add_hotkey('ctrl + alt + o', func_called)
    for symbol in excel_file:
        word_data = func(word)
        time.sleep(1)
        dict_of_data.append(word_data)
        
    return dict_of_data