• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

boppreh/keyboard: Hook and simulate global keyboard events on Windows and Linux.

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

boppreh/keyboard

开源软件地址(OpenSource Url):

https://github.com/boppreh/keyboard

开源编程语言(OpenSource Language):

Python 99.7%

开源软件介绍(OpenSource Introduction):

keyboard

Take full control of your keyboard with this small Python library. Hook global events, register hotkeys, simulate key presses and much more.

Features

  • 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).

Usage

Install the PyPI package:

pip install keyboard

or clone the repository (no installation required, source files are sufficient):

git clone https://github.com/boppreh/keyboard

or download and extract the zip into your project folder.

Then check the API docs below to see what features are available.

Example

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('@@', '[email protected]')

# 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

Known limitations:

  • 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.

Common patterns and mistakes

Preventing the program from closing

import keyboard
keyboard.add_hotkey('space', lambda: print('space was pressed!'))
# If the program finishes, the hotkey is not in effect anymore.

# Don't do this! This will use 100% of your CPU.
#while True: pass

# Use this instead
keyboard.wait()

# or this
import time
while True:
    time.sleep(1000000)

Waiting for a key press one time

import keyboard

# Don't do this! This will use 100% of your CPU until you press the key.
#
#while not keyboard.is_pressed('space'):
#    continue
#print('space was pressed, continuing...')

# Do this instead
keyboard.wait('space')
print('space was pressed, continuing...')

Repeatedly waiting for a key press

import keyboard

# Don't do this!
#
#while True:
#    if keyboard.is_pressed('space'):
#        print('space was pressed!')
#
# This will use 100% of your CPU and print the message many times.

# Do this instead
while True:
    keyboard.wait('space')
    print('space was pressed! Waiting on it again...')

# or this
keyboard.add_hotkey('space', lambda: print('space was pressed!'))
keyboard.wait()

Invoking code when an event happens

import keyboard

# Don't do this! This will call `print('space')` immediately then fail when the key is actually pressed.
#keyboard.add_hotkey('space', print('space was pressed'))

# Do this instead
keyboard.add_hotkey('space', lambda: print('space was pressed'))

# or this
def on_space():
    print('space was pressed')
keyboard.add_hotkey('space', on_space)

# or this
while True:
    # Wait for the next event.
    event = keyboard.read_event()
    if event.event_type == keyboard.KEY_DOWN and event.name == 'space':
        print('space was pressed')

'Press any key to continue'

# Don't do this! The `keyboard` module is meant for global events, even when your program is not in focus.
#import keyboard
#print('Press any key to continue...')
#keyboard.get_event()

# Do this instead
input('Press enter to continue...')

# Or one of the suggestions from here
# https://stackoverflow.com/questions/983354/how-to-make-a-script-wait-for-a-pressed-key

API

Table of Contents

keyboard.KEY_DOWN

= 'down'

keyboard.KEY_UP

= 'up'

class keyboard.KeyboardEvent

KeyboardEvent.device

KeyboardEvent.event_type

KeyboardEvent.is_keypad

KeyboardEvent.modifiers

KeyboardEvent.name

KeyboardEvent.scan_code

KeyboardEvent.time

KeyboardEvent.to_json(self, ensure_ascii=False)

[source]

keyboard.all_modifiers

= {'alt', 'alt gr', 'ctrl', 'left alt', 'left ctrl', 'left shift', 'left windows', 'right alt', 'right ctrl', 'right shift', 'right windows', 'shift', 'windows'}

keyboard.sided_modifiers

= {'alt', 'ctrl', 'shift', 'windows'}

keyboard.version

= '0.13.5'

keyboard.is_modifier(key)

[source]

Returns True if key is a scan code or name of a modifier key.

keyboard.key_to_scan_codes(key, error_if_missing=True)

[source]

Returns a list of scan codes associated with this key (name or scan code).

keyboard.parse_hotkey(hotkey)

[source]

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,))

keyboard.send(hotkey, do_press=True, do_release=True)

[source]

Sends OS events that perform the given 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').
  • do_press if true then press events are sent. Defaults to True.
  • do_release if true then release events are sent. Defaults to True.
send(57)
send('ctrl+alt+del')
send('alt+F4, enter')
send('shift+s')

Note: keys are released in the opposite order they were pressed.

keyboard.press(hotkey)

[source]

Presses and holds down a hotkey (see send).

keyboard.release(hotkey)

[source]

Releases a hotkey (see send).

keyboard.is_pressed(hotkey)

[source]

Returns True if the key is pressed.

is_pressed(57) #-> True
is_pressed('space') #-> True
is_pressed('ctrl+space') #-> True

keyboard.call_later(fn, args=(), delay=0.001)

[source]

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.

keyboard.hook(callback, suppress=False, on_remove=<lambda>)

[source]

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.

keyboard.on_press(callback, suppress=False)

[source]

Invokes callback for every KEY_DOWN event. For details see hook.

keyboard.on_release(callback, suppress=False)

[source]

Invokes callback for every KEY_UP event. For details see hook.

keyboard.hook_key(key, callback, suppress=False)

[source]

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.

keyboard.on_press_key(key, callback, suppress=False)

[source]

Invokes callback for KEY_DOWN event related to the given key. For details see hook.

keyboard.on_release_key(key, callback, suppress=False)

[source]

Invokes callback for KEY_UP event related to the given key. For details see hook.

keyboard.unhook(remove)

[source]

Removes a previously added hook, either by callback or by the return value of hook.

keyboard.unhook_all()

[source]

Removes all keyboard hooks in use, including hotkeys, abbreviations, word listeners, recorders and waits.

keyboard.block_key(key)

[source]

Suppresses all key events of the given key, regardless of modifiers.

keyboard.remap_key(src, dst)

[source]

Whenever the key src is pressed or released, regardless of modifiers, press or release the hotkey dst instead.


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap