control a keyboard python code example

Example 1: python type on keyboard

pip install keyboard

import keyboard

keyboard.press_and_release('shift+s, space')

keyboard.write('The quick brown fox jumps over the lazy dog.')

keyboard.add_hotkey('ctrl+shift+a', print, args=('triggered', 'hotkey'))

# Press PAGE UP then PAGE DOWN to type "foobar".
keyboard.add_hotkey('page up, page down', lambda: keyboard.write('foobar'))

# Blocks until you press esc.

# Record events until 'esc' is pressed.
recorded = keyboard.record(until='esc')
# Then replay back at three times the speed., speed_factor=3)

# Type @@ then press space to replace with abbreviation.
keyboard.add_abbreviation('@@', '[email protected]')

# Block forever, like `while True`.

Example 2: python library to control keyboard

from pynput.keyboard import Key, Controller

keyboard = Controller()

# Press and release space

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

# Type two upper case As'A')
with keyboard.pressed(Key.shift):'a')

# Type 'Hello World' using the shortcut type method
keyboard.type('Hello World')