Use the keyboard module to simulate and record keyboard operations

Use the keyboard module to simulate and record keyboard operations

The introduction is the keyboard module

Features of this module:

  • Global hook on all keyboard events (keys are captured regardless of focus).
  • Listen for and send keyboard events
  • Pure Python, no need to compile c modules
  • Zero dependencies. Installation and deployment is simple, just copying files.
  • Record playback button operation

1. Installation

pip install keyboard

2. Basic operation

1.) Press and release

>>> import keyboard
>>> keyboard.press_and_release('capslock')

After execution, it will simulate opening or closing the caps lock key

2.) Block forever, equivalent to while True:

>>> import keyboard
>>> keyboard.wait()

3.) Enter text

>>> import keyboard
>>> keyboard.write('Hello CSDN')

4.) Wait for the key press and respond

# 以下程序会监控热键ctrl+9 当你按下热键时,执行第二个参数的函数,将args作为参数传入该函数,直到按ESC键结束等待
>>> import keyboard
>>> keyboard.add_hotkey('ctrl+9', print, args=('你按下热键ctrl+9啦'))
<function add_hotkey.<locals>.remove_ at 0x0000016CEE2992D0>
>>> keyboard.wait('esc')
你 按 下 热 键 c t r l + 9
你 按 下 热 键 c t r l + 9
你 按 下 热 键 c t r l + 9>>> 
# 以下为清除热键
>>> keyboard.clear_hotkey('ctrl+9')
# 以下为清除所有热键
>>> keyboard.clear_all_hotkeys()

5.) Record keystrokes and play them back

>>> import keyboard
# 记录键盘的操作,直到按ESC
>>> recorded = keyboard.record(until='esc')
# 回放操作
>>> keyboard.play(recorded, speed_factor=3)

After you try to run the program, the password you enter to log in to the application will be recorded. After you press ESC to end, and then playback, the password you typed on the keyboard will be fully exposed.

6.) Enter @@, then press space, replace @@ with "Hello, CSDN"

>>> import keyboard
>>> keyboard.add_abbreviation('@@', 'Hello, CSDN')

API reference address of this module: https://github.com/boppreh/keyboard#api

Guess you like

Origin blog.csdn.net/chinagaobo/article/details/127295545