python key pressing library code example

Example 1: python get key module

import getkey, os
def clear():
  if os.name == "nt":
    _ = os.system('cls') #Clear function
  else:
    _ = os.system('clear')
current = "" 
while True:
  clear() #Clearing, required at beginning at end in order for algorithm to work
  print(current)
  key = getkey.key() # Gets the key
  if key == getkey.keys.BACKSPACE: # Detects if key is backspace
    current = current[:-1]
  elif key == getkey.keys.ENTER: # Detecs if key is the enter(return) key
    break
  else:
    current = current + key # Otherwise, adds on the the current variable
  clear()
clear()
print("\n\n\n You typed: " + current)

Example 2: how to execute key combinations with keyboard python lib

from pynput.keyboard import Key, Controller

keyboard = Controller()

# Press and release space
keyboard.press(Key.space)
keyboard.release(Key.space)

# Type a lower case A; this will work even if no key on the
# physical keyboard is labelled 'A'
keyboard.press('a')
keyboard.release('a')

# Type two upper case As
keyboard.press('A')
keyboard.release('A')
with keyboard.pressed(Key.shift):
    keyboard.press('a')
    keyboard.release('a')
    
# Press keys with hex, code in: https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
keyboard.press(KeyCode.from_vk(0x5C))
keyboard.press(KeyCode.from_vk(0x27))
keyboard.release(KeyCode.from_vk(0x27))
keyboard.release(KeyCode.from_vk(0x5C))
    
# Type 'Hello World' using the shortcut type method
keyboard.type('Hello World')