Search code examples
pythonpython-3.xtextcopy-paste

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.


Solution

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