Take full control of your keyboard with this small Python library. Hook global events, register hotkeys, simulate key presses and much more. 使用这个小Python库可以完全控制键盘。钩住全局事件,注册热键,模拟按键等等。
- Global event hook on all keyboards (captures keys regardless of focus).
- Listen and send keyboard events.
- Works with Windows and Linux (requires sudo), with experimental OS X support (thanks @glitchassassin!).
- Pure Python, no C modules to be compiled.
- Zero dependencies. Trivial to install and deploy, just copy the files.
- Python 2 and 3.
- Complex hotkey support (e.g.
ctrl+shift+m, ctrl+space
) with controllable timeout. - Includes high level API (e.g. record and play, add_abbreviation).
- Maps keys as they actually are in your layout, with full internationalization support (e.g.
Ctrl+ç
). - Events automatically captured in separate thread, doesn't block main program.
- Tested and documented.
- Doesn't break accented dead keys (I'm looking at you, pyHook).
- Mouse support available via project mouse (
pip install mouse
).
- Global event hook 在所有键盘上(无论焦点如何捕捉按键)。
- Listen and send 键盘事件 (监听和发送)
- 使用 Windows 和 Linux (需要 sudo), 实验性的 OS X 支持 (感谢 @glitchassassin!).
- Pure Python, 没有要编译的C模块。(纯python)
- Zero dependencies. 安装和部署很简单,只需复制文件即可。
- Python 2 and 3.
-复杂的热键支持 (例如
ctrl+shift+m, ctrl+space
) 具有可控超时。 - 包括 high level API (例如 record 和 play, add_abbreviation).
- 将关键点映射为它们在布局中的实际位置, 具有 完全国际化支持 (例如
Ctrl+ç
). - 事件在单独的线程中自动捕获,不会阻塞主程序。
- 测试和记录。
- 不会破坏重音死键 (我说的就是你, pyHook).
- 鼠标支持通过此项目提供 mouse (
pip install mouse
).
安装 PyPI package:
pip install keyboard
或者克隆存储库 (无需安装,源文件足够):
git clone https://github.com/boppreh/keyboard
或者 下载并解压缩zip 到项目文件夹中。
然后检查 API文档如下 查看哪些功能可用。
Use as library:
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.
keyboard.wait('esc')
# Record events until 'esc' is pressed.
recorded = keyboard.record(until='esc')
# Then replay back at three times the speed.
keyboard.play(recorded, speed_factor=3)
# Type @@ then press space to replace with abbreviation.
keyboard.add_abbreviation('@@', 'my.long.email@example.com')
# Block forever, like `while True`.
keyboard.wait()
Use as standalone module:
# Save JSON events to a file until interrupted:
python -m keyboard > events.txt
cat events.txt
# {"event_type": "down", "scan_code": 25, "name": "p", "time": 1622447562.2994788, "is_keypad": false}
# {"event_type": "up", "scan_code": 25, "name": "p", "time": 1622447562.431007, "is_keypad": false}
# ...
# Replay events
python -m keyboard < events.txt
- Events generated under Windows don't report device id (
event.device == None
). #21 - Media keys on Linux may appear nameless (scan-code only) or not at all. #20
- Key suppression/blocking only available on Windows. #22
- To avoid depending on X, the Linux parts reads raw device files (
/dev/input/input*
) but this requires root. - Other applications, such as some games, may register hooks that swallow all key events. In this case
keyboard
will be unable to report events. - This program makes no attempt to hide itself, so don't use it for keyloggers or online gaming bots. Be responsible.
- SSH connections forward only the text typed, not keyboard events. Therefore if you connect to a server or Raspberry PI that is running
keyboard
via SSH, the server will not detect your key events.
- 在Windows下生成的事件不报告设备id (
event.device == None
). #21 - Linux上的媒体控制按键可能会显示为无名(仅扫描代码)或根本不存在 #20
- 按键抑制/锁定(suppression/blocking)仅在Windows上可用 #22
- 为了避免依赖于X,Linux部件读取原始设备文件(
/dev/input/input*
),但这需要root。 - 其他应用程序,如一些游戏,可能会注册吞下所有关键事件的钩子。在这种情况下,
keyboard
将无法报告事件。 - 这个程序没有试图隐藏自己,所以不要使用它的键盘记录器或在线游戏机器人。负责任。
- SSH 连接只转发键入的文本,而不转发键盘事件。因此,如果您运行
keyboard
通过SSH,连接服务器或者树莓派,服务器将无法检测到您的按键事件
import keyboard
keyboard.add_hotkey('space', lambda: print('space was pressed!'))
# 如果程序完成,热键将不再有效。
# 别这样!这将使用100%的CPU。
#while True: pass
# 改用这个
keyboard.wait()
# 或者这个
import time
while True:
time.sleep(1000000)
import keyboard
# 别这样!这将使用100%的CPU,直到你按下键。
#
#while not keyboard.is_pressed('space'):
# continue
#print('空格按下, 继续...')
# 改为这样做
keyboard.wait('space')
print('空格按下, 继续...')
import keyboard
# 别这样!
#
#while True:
# if keyboard.is_pressed('space'):
# print('空格按下!')
#
# 这将使用100%的CPU和打印消息多次。
# 改为这样做
while True:
keyboard.wait('space')
print('space was pressed! Waiting on it again...')
# 或者这个
keyboard.add_hotkey('space', lambda: print('space was pressed!'))
keyboard.wait()
import keyboard
# 别这样!这将立即调用“print('space')”,然后在实际按键时失败。
#keyboard.add_hotkey('space', print('space was pressed'))
# 改为这样做
keyboard.add_hotkey('space', lambda: print('space was pressed'))
# 或者这样做
def on_space():
print('space was pressed')
keyboard.add_hotkey('space', on_space)
# 别这样!“keyboard”模块用于全局事件,即使您的程序没有焦点。
#import keyboard
#print('Press any key to continue...')
#keyboard.get_event()
#改为这样做
input('Press enter to continue...')
# 或者这里的一个建议
# https://stackoverflow.com/questions/983354/how-to-make-a-script-wait-for-a-pressed-key
- keyboard.KEY_DOWN按键按下
- keyboard.KEY_UP按键上升
- keyboard.KeyboardEvent键盘事件
- keyboard.all_modifiers所有修饰符
- keyboard.sided_modifiers侧边修饰符
- keyboard.version版本
- keyboard.is_modifier是否修饰符
- keyboard.key_to_scan_codes按键到扫描 代码
- keyboard.parse_hotkey解析热键
- keyboard.send发送 (aliases:
press_and_release
) - keyboard.press按
- keyboard.release释放
- keyboard.is_pressed是否按下
- keyboard.call_later稍后执行
- keyboard.hook钩子
- keyboard.on_press按下
- keyboard.on_release释放
- keyboard.hook_key钩子 键
- keyboard.on_press_key按键按下回调
- keyboard.on_release_key按键释放回调
- keyboard.unhook脱钩 (aliases:
unblock_key
,unhook_key
,unremap_key
) - keyboard.unhook_all脱钩所有
- keyboard.block_key拦截键
- keyboard.remap_key重新映射键
- keyboard.parse_hotkey_combinations解析热键组合
- keyboard.add_hotkey新增热键 (aliases:
register_hotkey
) - keyboard.remove_hotkey移除热键 (aliases:
clear_hotkey
,unregister_hotkey
,unremap_hotkey
) - keyboard.unhook_all_hotkeys解开所有热键 (aliases:
clear_all_hotkeys
,remove_all_hotkeys
,unregister_all_hotkeys
) - keyboard.remap_hotkey重新映射热键
- keyboard.stash_state隐藏状态
- keyboard.restore_state还原状态
- keyboard.restore_modifiers还原修饰键
- keyboard.write写入
- keyboard.wait等待
- keyboard.get_hotkey_name读取热键名称
- keyboard.read_event读取事件
- keyboard.read_key读取键
- keyboard.read_hotkey读取热键
- keyboard.get_typed_strings获取输入字符串
- keyboard.start_recording开始录制
- keyboard.stop_recording停止录制
- keyboard.record记录
- keyboard.play播放 (aliases:
replay
) - keyboard.add_word_listener新增文字监听 (aliases:
register_word_listener
) - keyboard.remove_word_listener移除文字监听 (aliases:
remove_abbreviation
) - keyboard.add_abbreviation新增缩写 (aliases:
register_abbreviation
) - keyboard.normalize_name规范化名称
= 'down'
= 'up'
= {'alt', 'alt gr', 'ctrl', 'left alt', 'left ctrl', 'left shift', 'left windows', 'right alt', 'right ctrl', 'right shift', 'right windows', 'shift', 'windows'}
= {'alt', 'ctrl', 'shift', 'windows'}
= '0.13.5'
Returns True if key
is a scan code or name of a modifier key.
如果key
是修饰符的扫描代码或名称,则返回True
Returns a list of scan codes associated with this key (name or scan code). 返回与此键关联的扫描代码列表(名称或扫描代码)。
Parses a user-provided hotkey into nested tuples representing the parsed structure, with the bottom values being lists of scan codes. Also accepts raw scan codes, which are then wrapped in the required number of nestings.
将用户提供的热键解析为表示解析的结构,底部的值是扫描代码列表。还接受原始扫描代码,然后将其包装在所需的嵌套数。
Example:
parse_hotkey("alt+shift+a, alt+b, c")
# Keys: ^~^ ^~~~^ ^ ^~^ ^ ^
# Steps: ^~~~~~~~~~^ ^~~~^ ^
# ((alt_codes, shift_codes, a_codes), (alt_codes, b_codes), (c_codes,))
Sends OS events that perform the given hotkey hotkey. 发送执行给定**hotkey*热键的操作系统事件。
hotkey
can be either a scan code (e.g. 57 for space), single key (e.g. 'space') or multi-key, multi-step hotkey (e.g. 'alt+F4, enter'). 可以是扫描代码(例如,57表示空格),单键(例如“空格”)或多键、多步热键(例如“alt+F4,enter”)。do_press
if true then press events are sent. Defaults to True.如果为true,则发送按下事件。默认为True。do_release
if true then release events are sent. Defaults to True.如果为true,则发送释放事件。默认为True。
send(57)
send('ctrl+alt+del')
send('alt+F4, enter')
send('shift+s')
注意:按键按相反的顺序释放。
Presses and holds down a hotkey (see send
).
Releases a hotkey (see send
).
Returns True if the key is pressed.
is_pressed(57) #-> True
is_pressed('space') #-> True
is_pressed('ctrl+space') #-> True
Calls the provided function in a new thread after waiting some time. Useful for giving the system some time to process an event, without blocking the current execution flow.
Installs a global listener on all available keyboards, invoking callback
each time a key is pressed or released.
The event passed to the callback is of type keyboard.KeyboardEvent
,
with the following attributes:
name
: an Unicode representation of the character (e.g. "&") or description (e.g. "space"). The name is always lower-case.scan_code
: number representing the physical key, e.g. 55.time
: timestamp of the time the event occurred, with as much precision as given by the OS.
Returns the given callback for easier development.
Invokes callback
for every KEY_DOWN event. For details see hook
.
Invokes callback
for every KEY_UP event. For details see hook
.
Hooks key up and key down events for a single key. Returns the event handler
created. To remove a hooked key use unhook_key(key)
or
unhook_key(handler)
.
Note: this function shares state with hotkeys, so clear_all_hotkeys
affects it as well.
Invokes callback
for KEY_DOWN event related to the given key. For details see hook
.
Invokes callback
for KEY_UP event related to the given key. For details see hook
.
Removes a previously added hook, either by callback or by the return value
of hook
.
Removes all keyboard hooks in use, including hotkeys, abbreviations, word
listeners, record
ers and wait
s.
Suppresses all key events of the given key, regardless of modifiers.
Whenever the key src
is pressed or released, regardless of modifiers,
press or release the hotkey dst
instead.
Parses a user-provided hotkey. Differently from parse_hotkey
,
instead of each step being a list of the different scan codes for each key,
each step is a list of all possible combinations of those scan codes.
Invokes a callback every time a hotkey is pressed. The hotkey must
be in the format ctrl+shift+a, s
. This would trigger when the user holds
ctrl, shift and "a" at once, releases, and then presses "s". To represent
literal commas, pluses, and spaces, use their names ('comma', 'plus',
'space').
args
is an optional list of arguments to passed to the callback during each invocation.suppress
defines if successful triggers should block the keys from being sent to other programs.timeout
is the amount of seconds allowed to pass between key presses.trigger_on_release
if true, the callback is invoked on key release instead of key press.
The event handler function is returned. To remove a hotkey call
remove_hotkey(hotkey)
or remove_hotkey(handler)
.
before the hotkey state is reset.
Note: hotkeys are activated when the last key is pressed, not released.
Note: the callback is executed in a separate thread, asynchronously. For an
example of how to use a callback synchronously, see wait
.
Examples:
# Different but equivalent ways to listen for a spacebar key press.
add_hotkey(' ', print, args=['space was pressed'])
add_hotkey('space', print, args=['space was pressed'])
add_hotkey('Space', print, args=['space was pressed'])
# Here 57 represents the keyboard code for spacebar; so you will be
# pressing 'spacebar', not '57' to activate the print function.
add_hotkey(57, print, args=['space was pressed'])
add_hotkey('ctrl+q', quit)
add_hotkey('ctrl+alt+enter, space', some_callback)
Removes a previously hooked hotkey. Must be called with the value returned
by add_hotkey
.
Removes all keyboard hotkeys in use, including abbreviations, word listeners,
record
ers and wait
s.
Whenever the hotkey src
is pressed, suppress it and send
dst
instead.
Example:
remap('alt+w', 'ctrl+up')
Builds a list of all currently pressed scan codes, releases them and returns
the list. Pairs well with restore_state
and restore_modifiers
.
Given a list of scan_codes ensures these keys, and only these keys, are
pressed. Pairs well with stash_state
, alternative to restore_modifiers
.
Like restore_state
, but only restores modifier keys.
Sends artificial keyboard events to the OS, simulating the typing of a given text. Characters not available on the keyboard are typed as explicit unicode characters using OS-specific functionality, such as alt+codepoint.
To ensure text integrity, all currently pressed keys are released before the text is typed, and modifiers are restored afterwards.
delay
is the number of seconds to wait between keypresses, defaults to no delay.restore_state_after
can be used to restore the state of pressed keys after the text is typed, i.e. presses the keys that were released at the beginning. Defaults to True.exact
forces typing all characters as explicit unicode (e.g. alt+codepoint or special events). If None, uses platform-specific suggested value.
Blocks the program execution until the given hotkey is pressed or, if given no parameters, blocks forever.
Returns a string representation of hotkey from the given key names, or the currently pressed keys if not given. This function:
- normalizes names;
- removes "left" and "right" prefixes;
- replaces the "+" key name with "plus" to avoid ambiguity;
- puts modifier keys first, in a standardized order;
- sort remaining keys;
- finally, joins everything with "+".
Example:
get_hotkey_name(['+', 'left ctrl', 'shift'])
# "ctrl+shift+plus"
Blocks until a keyboard event happens, then returns that event.
Blocks until a keyboard event happens, then returns that event's name or, if missing, its scan code.
Similar to read_key()
, but blocks until the user presses and releases a
hotkey (or single key), then returns a string representing the hotkey
pressed.
Example:
read_hotkey()
# "ctrl+shift+p"
Given a sequence of events, tries to deduce what strings were typed.
Strings are separated when a non-textual key is pressed (such as tab or
enter). Characters are converted to uppercase according to shift and
capslock status. If allow_backspace
is True, backspaces remove the last
character typed.
This function is a generator, so you can pass an infinite stream of events and convert them to strings in real time.
Note this functions is merely an heuristic. Windows for example keeps per- process keyboard state such as keyboard layout, and this information is not available for our hooks.
get_type_strings(record()) #-> ['This is what', 'I recorded', '']
Starts recording all keyboard events into a global variable, or the given queue if any. Returns the queue of events and the hooked function.
Use stop_recording()
or unhook(hooked_function)
to stop.
Stops the global recording of events and returns a list of the events captured.
Records all keyboard events from all keyboards until the user presses the
given hotkey. Then returns the list of events recorded, of type
keyboard.KeyboardEvent
. Pairs well with
play(events)
.
Note: this is a blocking function.
Note: for more details on the keyboard hook and events see hook
.
Plays a sequence of recorded events, maintaining the relative time
intervals. If speed_factor is <= 0 then the actions are replayed as fast
as the OS allows. Pairs well with record()
.
Note: the current keyboard state is cleared at the beginning and restored at the end of the function.
Invokes a callback every time a sequence of characters is typed (e.g. 'pet') and followed by a trigger key (e.g. space). Modifiers (e.g. alt, ctrl, shift) are ignored.
word
the typed text to be matched. E.g. 'pet'.callback
is an argument-less function to be invoked each time the word is typed.triggers
is the list of keys that will cause a match to be checked. If the user presses some key that is not a character (len>1) and not in triggers, the characters so far will be discarded. By default the trigger is onlyspace
.match_suffix
defines if endings of words should also be checked instead of only whole words. E.g. if true, typing 'carpet'+space will trigger the listener for 'pet'. Defaults to false, only whole words are checked.timeout
is the maximum number of seconds between typed characters before the current word is discarded. Defaults to 2 seconds.
Returns the event handler created. To remove a word listener use
remove_word_listener(word)
or remove_word_listener(handler)
.
Note: all actions are performed on key down. Key up events are ignored. Note: word matches are case sensitive.
Removes a previously registered word listener. Accepts either the word used
during registration (exact string) or the event handler returned by the
add_word_listener
or add_abbreviation
functions.
Registers a hotkey that replaces one typed text with another. For example
add_abbreviation('tm', u'™')
Replaces every "tm" followed by a space with a ™ symbol (and no space). The replacement is done by sending backspace events.
match_suffix
defines if endings of words should also be checked instead of only whole words. E.g. if true, typing 'carpet'+space will trigger the listener for 'pet'. Defaults to false, only whole words are checked.timeout
is the maximum number of seconds between typed characters before the current word is discarded. Defaults to 2 seconds.
For more details see add_word_listener
.
Given a key name (e.g. "LEFT CONTROL"), clean up the string and convert to the canonical representation (e.g. "left ctrl") if one is known.