keyboard python documentation code example
Example 1: python keyboard press
import keyboard
import time
stop = False
def onkeypress(event):
global stop
if event.name == 'q':
stop = True
keyboard.on_press(onkeypress)
while True:
try:
print("sleeping")
time.sleep(5)
print("slept")
if stop:
print('You Pressed A Key!')
break
except:
print("#######")
break
Example 2: how to execute key combinations with keyboard python lib
from pynput.keyboard import Key, Controller
keyboard = Controller()
keyboard.press(Key.space)
keyboard.release(Key.space)
keyboard.press('a')
keyboard.release('a')
keyboard.press('A')
keyboard.release('A')
with keyboard.pressed(Key.shift):
keyboard.press('a')
keyboard.release('a')
keyboard.press(KeyCode.from_vk(0x5C))
keyboard.press(KeyCode.from_vk(0x27))
keyboard.release(KeyCode.from_vk(0x27))
keyboard.release(KeyCode.from_vk(0x5C))
keyboard.type('Hello World')
Example 3: module to read keyboard
import keyboard
while True:
try:
if keyboard.is_pressed('q'):
print('You Pressed A Key!')
break
except:
break
Example 4: python keyboard.write
keyboard.write('The quick brown fox jumps over the lazy dog.')
Example 5: python library to control keyboard
from pynput.keyboard import Key, Controller
keyboard = Controller()
keyboard.press(Key.space)
keyboard.release(Key.space)
keyboard.press('a')
keyboard.release('a')
keyboard.press('A')
keyboard.release('A')
with keyboard.pressed(Key.shift):
keyboard.press('a')
keyboard.release('a')
keyboard.type('Hello World')