Search on blog:

Python: How to use pynput to get phrase of few chars

Some modules have function to catch single char and assign function but they don't have function to catch few chars which create phrase.

This is example uses pynput Listener to catch all pressed chars and keep them in string - and this helps to check if few last chars match some phrase. But it doesn't check if phrase is not part of longer phrase.

from pynput import keyboard

# keep all chars in global variable
all_keys = ""

def on_press(key):
    global all_keys

        all_keys += key.char

        if all_keys.endswith("open me"):
            print("I open Sesame")

    except AttributeError:
        #print('special key {0} pressed'.format(key))

        # space doesn't have `key.char`
        if key ==
            all_keys += ' '

def on_release(key):
    #print('{0} released'.format(key))
    if key == keyboard.Key.esc:
        # Stop listener
        return False

# Collect events until released
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    # ... other code ...

On Linux there is program in Python AutoKey which catch text (phrase) and replace it with other text (it is so called "text expansion").

On Windows there is similar program but not in Python AutoHotKey and it is even more powerful then AutoKey because it can use combination of keys with mouse buttons.

Both can be useful to fast putting full code in place of short text (so called "snippets").


pynput: Monitoring the keyboard

Wikipedia: AutoHotKey

GitHub: AutoHotKey

If you like it
Buy a Coffee