使用python创建热键以输入文本,在后台运行等待按键

nat*_*eph 5 python text copy-paste python-3.x

我正在尝试使用 python 应用程序模拟我的操作系统的复制/粘贴功能。

我想要发生的是,当我按下按键时,比如“Alt-X”,它会将预定义的文本粘贴到当前占用的文本字段中。基本上是复制和粘贴,但创建我自己的。

我试过使用 pyautogui 和其他框架,但我似乎无法弄清楚如何让它在后台等待按键,然后输入文本。

有任何想法吗?谢谢。

Pra*_*mar 6

尝试键盘库:

import keyboard

text_to_print='default_predefined_text'
shortcut = 'alt+x' #define your hot-key
print('Hotkey set as:', shortcut)

def on_triggered(): #define your function to be executed on hot-key press
    print(text_to_print)
    #write_to_textfield(text_to_print) #<-- your function
keyboard.add_hotkey(shortcut, on_triggered) #<-- attach the function to hot-key

print("Press ESC to stop.")
keyboard.wait('esc')
Run Code Online (Sandbox Code Playgroud)

以上将在终端中打印预定义的文本。

sudoie执行脚本sudo python program_name.py

安装 :

sudo pip 安装键盘

注意:根据文档“适用于 Windows 和 Linux(需要 sudo),具有实验性 OS X 支持