【问题标题】:Checking for keypress while a function is running在函数运行时检查按键
【发布时间】:2021-05-04 02:06:11
【问题描述】:

我有这个功能可以运行大约一个小时左右。 我需要一种在 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

【问题讨论】:

  • 我不知道在 python 中是否有特定的方法可以做,但是这个长时间运行的进程(interrumpible 与否)的标准方法是创建一个线程。对于 python,例如你可以查看this tutorial
  • 这能回答你的问题吗? How to kill a while loop with a keystroke?
  • @DaanSeuntjens 我真的不想终止循环,我想暂停它以便调用另一个函数并继续循环。每个循环大约需要 2 秒,我可以在很小的时间范围内使用 keyboard.is_pressed('some key')。
  • @Sourcerer 实际上我确实尝试过线程,但是当第一个函数使用按键组合运行时,我无法调用另一个函数。考虑到我对线程相当陌生,我可能没有正确实现它。我会再试一次。谢谢!

标签: python keyboard keypress


【解决方案1】:

热键似乎已经解决了这个问题。另外,我不必提出 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-15
    • 2010-10-05
    • 1970-01-01
    相关资源
    最近更新 更多