【问题标题】:Call python function with hotkey使用热键调用 python 函数
【发布时间】:2022-08-03 00:21:59
【问题描述】:

我想用热键调用 python 函数或 python 文件来执行。我的功能是一个无限循环。我也想用热键终止执行。可能吗?

Windows 快捷方式不是一个选项,因为我想选择 1 个键来执行而不是组合键(例如 CRTL + SHIFT + L )。

如果热键是鼠标的中间(滚动)按钮,那就太好了。

  • 使用 wxPython 注册一个全局热键。我不知道是否可以分配单键或鼠标按钮。但如果没有,您可以编写一个键盘记录器来完成它。或者使用 autohotkey 等外部工具与您的程序进行通信。也就是说,如果您要询问的是系统范围的热键。在窗口处于活动状态时获取鼠标、按键、操纵杆、MIDI 和其他硬件事件很容易。

标签: python python-3.x automation pyautogui


【解决方案1】:

您可以使用 mouse 模块 (pip install mouse) 设置热键。要在循环中运行函数然后再次按热键停止,您需要创建一个新线程 (intro to threading) 来运行此循环。然后,当再次按下热键时,您将需要使用一个事件来停止该线程的执行。下面是执行此操作的示例。

import mouse  # pip install mouse
import threading
import time

    
def your_function():
    # the function you want to execute in the loop
    print("Executing your function...")
    time.sleep(0.9)  # You will probably want to remove this

def repeat_function(kill_event):
    print("Starting loop...")
    while not kill_event.is_set():
        your_function()
    print("Exiting loop...")
    

while True:
    print("Waiting for hotkey press...")
    kill_event = threading.Event()
    new_thread = threading.Thread(target= lambda: repeat_function(kill_event))

    # set the hotkey that will start the loop to middle mouse button
    start_hook = mouse.on_middle_click(new_thread.start)
    mouse.wait(mouse.MIDDLE)   # wait till the hotkey gets pressed
    time.sleep(0.3)    # important, otherwise will get cancelled instantly
    mouse.unhook(start_hook)   # clear the old hotkey

    # set the hotkey to kill the loop instead
    end_hook = mouse.on_middle_click(kill_event.set)
    mouse.wait(mouse.MIDDLE)
    new_thread.join()        # wait for thread to fully finish
    mouse.unhook(end_hook)   # remove kill hotkey and start again

【讨论】:

    猜你喜欢
    • 2012-11-15
    • 2014-06-15
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    相关资源
    最近更新 更多