furas

Python - pynput - catch text "open me"

Jan 6th, 2021 (edited)
672
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # author: Bartlomiej "furas" Burek (https://blog.furas.pl)
  2. # date: 2021.01.06
  3. # https://stackoverflow.com/questions/65595355/how-can-i-detect-if-several-keys-are-pressed-in-a-particular-order-with-python
  4.  
  5. # example code to catch text `"open me"`
  6.  
  7. from pynput import keyboard
  8.  
  9. all_keys = ""
  10.  
  11. def on_press(key):
  12.     global all_keys
  13.    
  14.     try:
  15.         all_keys += key.char
  16.         all_keys = all_keys[-7:]  
  17.         if all_keys == "open me":
  18.             print("I open Sesame")
  19.     except AttributeError:
  20.         if key == keyboard.Key.space:
  21.             all_keys += ' '
  22.         #print('special key {0} pressed'.format(key))
  23.  
  24. def on_release(key):
  25.     #print('{0} released'.format(key))
  26.     if key == keyboard.Key.esc:
  27.         # Stop listener
  28.         return False
  29.  
  30. # Collect events until released
  31. with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
  32.     # ... code ...
  33.     listener.join()
  34.  
RAW Paste Data