Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a hotkey to enter text using python, running in background waiting for key-press

I'm trying to emulate the copy/paste functionality of my OS using a python application.

What I want to have happen is that when I press the keys, say, "Alt-X", it would paste predefined text into the currently occupied text field. Basically copy and paste but creating my own.

I've tried using pyautogui and other frameworks but I can't seem to figure out how get it to wait for key-press in the background, and then enter the text after that.

Any ideas? Thanks.

like image 333
nateph Avatar asked Feb 21 '18 21:02

nateph


1 Answers

Try keyboard library :

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')

the above will print a predefined text into the terminal.

execute the script with sudo i.e. sudo python program_name.py

installation :

sudo pip install keyboard

Note : According to documentation 'Works with Windows and Linux (requires sudo), with experimental OS X support'

like image 75
Pratik Kumar Avatar answered Oct 19 '22 19:10

Pratik Kumar