在等待按键的后台使用 python、运行 创建热键以输入文本
Creating a hotkey to enter text using python, running in background waiting for key-press
我正在尝试使用 python 应用程序模拟我的 OS 的 copy/paste 功能。
我想要发生的是,当我按下按键时,例如 "Alt-X",它会将预定义的文本粘贴到当前占用的文本字段中。基本上复制和粘贴,但创建我自己的。
我试过使用 pyautogui 和其他框架,但我似乎无法弄清楚如何让它在后台等待按键,然后输入文本。
有什么想法吗?谢谢
尝试 keyboard 库:
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')
以上将在终端中打印预定义的文本。
使用 sudo
执行脚本,即 sudo python program_name.py
安装:
sudo pip install keyboard
注意 :根据文档'Works with Windows and Linux (requires sudo), with experimental OS X支持'
我正在尝试使用 python 应用程序模拟我的 OS 的 copy/paste 功能。
我想要发生的是,当我按下按键时,例如 "Alt-X",它会将预定义的文本粘贴到当前占用的文本字段中。基本上复制和粘贴,但创建我自己的。
我试过使用 pyautogui 和其他框架,但我似乎无法弄清楚如何让它在后台等待按键,然后输入文本。
有什么想法吗?谢谢
尝试 keyboard 库:
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')
以上将在终端中打印预定义的文本。
使用 sudo
执行脚本,即 sudo python program_name.py
安装:
sudo pip install keyboard
注意 :根据文档'Works with Windows and Linux (requires sudo), with experimental OS X支持'