Hook and simulate global keyboard events on Windows and Linux.

Overview

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

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

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.

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.

keyboard.parse_hotkey_combinations(hotkey)

[source]

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.

keyboard.add_hotkey(hotkey, callback, args=(), suppress=False, timeout=1, trigger_on_release=False)

[source]

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)

keyboard.remove_hotkey(hotkey_or_callback)

[source]

Removes a previously hooked hotkey. Must be called with the value returned by add_hotkey.

keyboard.unhook_all_hotkeys()

[source]

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

keyboard.remap_hotkey(src, dst, suppress=True, trigger_on_release=False)

[source]

Whenever the hotkey src is pressed, suppress it and send dst instead.

Example:

remap_hotkey('alt+w', 'ctrl+up')

keyboard.stash_state()

[source]

Builds a list of all currently pressed scan codes, releases them and returns the list. Pairs well with restore_state and restore_modifiers.

keyboard.restore_state(scan_codes)

[source]

Given a list of scan_codes ensures these keys, and only these keys, are pressed. Pairs well with stash_state, alternative to restore_modifiers.

keyboard.restore_modifiers(scan_codes)

[source]

Like restore_state, but only restores modifier keys.

keyboard.write(text, delay=0, restore_state_after=True, exact=None)

[source]

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.

keyboard.wait(hotkey=None, suppress=False, trigger_on_release=False)

[source]

Blocks the program execution until the given hotkey is pressed or, if given no parameters, blocks forever.

keyboard.get_hotkey_name(names=None)

[source]

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"

keyboard.read_event(suppress=False)

[source]

Blocks until a keyboard event happens, then returns that event.

keyboard.read_key(suppress=False)

[source]

Blocks until a keyboard event happens, then returns that event's name or, if missing, its scan code.

keyboard.read_hotkey(suppress=True)

[source]

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"

keyboard.get_typed_strings(events, allow_backspace=True)

[source]

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', '']

keyboard.start_recording(recorded_events_queue=None)

[source]

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.

keyboard.stop_recording()

[source]

Stops the global recording of events and returns a list of the events captured.

keyboard.record(until='escape', suppress=False, trigger_on_release=False)

[source]

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.

keyboard.play(events, speed_factor=1.0)

[source]

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.

keyboard.add_word_listener(word, callback, triggers=['space'], match_suffix=False, timeout=2)

[source]

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

keyboard.remove_word_listener(word_or_handler)

[source]

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.

keyboard.add_abbreviation(source_text, replacement_text, match_suffix=False, timeout=2)

[source]

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.

keyboard.normalize_name(name)

[source]

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.

Comments
  • Windows support

    Windows support

    Hi,

    This pure-python, cross-platform lib is quite impressive. It could help a lot on workstations where adding stuff is severely restricted (ie no pip, etc.).

    One thing I'm looking for is to reproduce (at least partly) the abbreviation expansion functionality found in Autohotkey (among others). This replaces text patterns as you type, without hotkeys (ie., type 'tm" followed by space and its gets replaced by a trademark symbol for example).

    I have not been able to do this using the add_hotkey method (which is probably normal). Could there be a way to achieve it using the lower-level functions ?

    TIA, fp

    opened by fpp-gh 68
  • Key mapping error on non-English Windows

    Key mapping error on non-English Windows

    Using Python2.7(32bits) on W10(64bits).

    The following is ok : keyboard.press('s')

    The following raises an exception : keyboard.press('shift+s')

    File "Z:\Eclipse\GamepadToKey\src\key_manager.py", line 25, in joy_set_button keyboard.press(buttons_tab[button]) File "Z:\Eclipse\GamepadToKey\src\keyboard_init.py", line 509, in press send(combination, True, False) File "Z:\Eclipse\GamepadToKey\src\keyboard_init_.py", line 501, in send os_keyboard.press(to_scan_code(key)) File "Z:\Eclipse\GamepadToKey\src\keyboard_init.py", line 479, in to_scan_code scan_code, modifiers = _os_keyboard.map_char(_normalize_name(key)) File "Z:\Eclipse\GamepadToKey\src\keyboard_winkeyboard.py", line 244, in map_char raise ValueError('Character {} is not mapped to any known key.'.format(repr(character))) ValueError: Character 'shift' is not mapped to any known key.

    Bug or Windows limitation ?

    opened by NicoPy 29
  • keyboard.wait() causes an error since the last package update

    keyboard.wait() causes an error since the last package update

    Exception in thread Thread-1:
    Traceback (most recent call last):
      File "C:\Users\rbedard\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 916, in _bootstrap_inner
        self.run()
      File "C:\Users\rbedard\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 864, in run
        self._target(*self._args, **self._kwargs)
      File "C:\Users\rbedard\AppData\Local\Programs\Python\Python36-32\lib\site-packages\keyboard\__init__.py", line 138, in listen
        _os_keyboard.listen(self.queue, _key_table.is_allowed)
      File "C:\Users\rbedard\AppData\Local\Programs\Python\Python36-32\lib\site-packages\keyboard\_winkeyboard.py", line 470, in listen
        prepare_intercept(lambda e: queue.put(e) or is_allowed(e.name, e.event_type == KEY_UP))
      File "C:\Users\rbedard\AppData\Local\Programs\Python\Python36-32\lib\site-packages\keyboard\_winkeyboard.py", line 451, in prepare_intercept
        keyboard_hook = SetWindowsHookEx(WH_KEYBOARD_LL, keyboard_callback, NULL, NULL)
    ctypes.ArgumentError: argument 2: <class 'TypeError'>: expected CFunctionType instance instead of CFunctionType
    

    I'm doing the following and I get the above exception when I hit the keyboard.wait line. I did not have a chance to dig in to figure out what was happening so I'm hoping someone can get to this before I am able to. This was working fine before I updated the keyboard package today.

    recorded = []
    keyboard.hook(recorded.append)
    mouse.hook(recorded.append)
    keyboard.wait('esc')
    
    opened by bobonthenet 21
  • nothing happens

    nothing happens

    hi, i am python newbie, and is very dificult to me understand how to run this program, so, i create a executable file on linux called k3y like this

    #!/usr/bin/python
    # coding: latin-1
    
    import keyboard
    
    # Press PAGE UP then PAGE DOWN to type "foobar".
    keyboard.add_hotkey('page up, page down', lambda: keyboard.write('foobar'))
    
    keyboard.add_hotkey('ctrl+q', quit)
    keyboard.add_hotkey('ctrl+alt+enter, space', u'some_callback')
    keyboard.add_abbreviation('tm', u'™')
    keyboard.add_abbreviation('3n', u'el3ctron') 
    

    so, i executed on my command line ./k3y it runs showing no error, but when i do some abreviation (for example writting in another window 3n), or pressing some hot key ('page up, page down') nothing happens! i do not know if i am doing something wrong. :(

    opened by el3ctron 21
  • Linux problems on basic example

    Linux problems on basic example

    Hi, me again :-) Got me a Linux laptop and trying to really use the lib on it, because of course, no AutoHotKey... Unfortunately I can't get it to run a two-line test example (import keyboard, define one abbreviation). With Python 2.7 it bombs:

    Exception in thread Thread-1:
    Traceback (most recent call last):
      File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
        self.run()
      File "/usr/lib/python2.7/threading.py", line 754, in run
        self.__target(*self.__args, **self.__kwargs)
      File "/home/fpp/python/PyHotKey/keyboard/__init__.py", line 114, in listen
        _os_keyboard.listen(self.queue)
      File "/home/fpp/python/PyHotKey/keyboard/_nixkeyboard.py", line 111, in listen
        build_device()
      File "/home/fpp/python/PyHotKey/keyboard/_nixkeyboard.py", line 106, in build_device
        device = aggregate_devices('kbd')
      File "/home/fpp/python/PyHotKey/keyboard/_nixcommon.py", line 145, in aggregate_devices
        uinput = make_uinput()
      File "/home/fpp/python/PyHotKey/keyboard/_nixcommon.py", line 48, in make_uinput
        uinput.read = lambda n: Queue().get()
    AttributeError: 'file' object attribute 'read' is read-only
    

    With Python3.5 there is no exception but no abbreviation expanding either...

    This is on XUbuntu 16.04, running the script as root in xterm and testing in Mousepad. Anything I'm doing wrong ?...

    opened by fpp-gh 16
  • Difference between read_hotkey and add_hotkey

    Difference between read_hotkey and add_hotkey

    I'm using this package to control a piece of hardware:

    adjust = True
    while adjust:
        if keyboard.read_key() == 'esc':
            adjust = False
    
        elif keyboard.read_key() == 'left':
            move_left()
    

    Now I would like to use hotkeys, e.g. something like

    adjust = True
    while adjust:
        if keyboard.read_key() == 'esc':
            adjust = False
    
        elif keyboard.read_key() == 'left':
            move_left()
    
        elif keyboard.read_key() == 'ctrl+left':    # Use read_hotkey, add_hotkey, or some other function?
            move_left_large_step()
    

    From the documentation, it's not clear which function to use and how. Specifically, what is the difference between read_hotkey and add_hotkey and which of these two is the right one?

    opened by danielbaumer 14
  • Can't map some keys

    Can't map some keys

    Hi, thanks for this library, I'm trying to make use of it to create a simple custom hotkey "alias". I'm on a MacBook Air running Linux (Gentoo).

    import keyboard
    import time
    
    keyboard.clear_all_hotkeys()
    
    keyboard.add_hotkey('win+c', lambda: keyboard.send('ctrl+c'))
    keyboard.add_hotkey('win+v', lambda: keyboard.send('ctrl+v'))
    
    keyboard.add_hotkey('win+l', lambda: keyboard.send('ctrl+l'))
    keyboard.add_hotkey('win+e', lambda: keyboard.send('ctrl+l'))
    
    while True:
        time.sleep(10)
    

    On the script above, win+l and win+e are calling the same keyboard hotkey but only win+e works. I'm hitting those hotkeys on Chrome browser.

    If I change those mappings to a debugger output:

    keyboard.add_hotkey('win+c', lambda: print('ctrl+c'))
    keyboard.add_hotkey('win+v', lambda: print('ctrl+v'))
    
    keyboard.add_hotkey('win+l', lambda: print('ctrl+l'))
    keyboard.add_hotkey('win+e', lambda: print('ctrl+l'))
    

    I do see the output on the console. Do you have any idea what could be cause these events to not be correctly processed by chrome?

    P.S.: I don't think it's relative to Chrome, as the same hotkeys don't work on other applications (e.g. termite).

    opened by bpinto 14
  • AttributeError: module 'keyboard._darwinkeyboard' has no attribute 'type_unicode'

    AttributeError: module 'keyboard._darwinkeyboard' has no attribute 'type_unicode'

    Hello, I am testing your "write.py" example on OSX Sierra 10.12.6. I tested this using the native python 2.7.10 and brew install of python 3 at 3.6.2. Used pip to install keyboard once in both python environments. Both had identical errors listed below.

    The program actually works, but then crashes with the following error:

    Traceback (most recent call last):
      File "/usr/local/lib/python3.6/site-packages/keyboard/__init__.py", line 570, in write
        scan_code, modifiers = _os_keyboard.map_char(letter)
      File "/usr/local/lib/python3.6/site-packages/keyboard/_darwinkeyboard.py", line 390, in map_char
        return key_controller.map_char(character)
      File "/usr/local/lib/python3.6/site-packages/keyboard/_darwinkeyboard.py", line 305, in map_char
        return self.key_map.character_to_vk(character)
      File "/usr/local/lib/python3.6/site-packages/keyboard/_darwinkeyboard.py", line 153, in character_to_vk
        raise ValueError("Unrecognized character: {}".format(character))
    ValueError: Unrecognized character: enter
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "write.py", line 14, in <module>
        keyboard.write(line)
      File "/usr/local/lib/python3.6/site-packages/keyboard/__init__.py", line 584, in write
        _os_keyboard.type_unicode(letter)
    AttributeError: module 'keyboard._darwinkeyboard' has no attribute 'type_unicode'
    

    I cannot tell if this is a configuration, dependency or other problem. But it is an issue with one of the standard examples.

    Thanks for your Open Source contributions.

    Regards, -FT

    bug osx waiting-for-feedback 
    opened by ftpersonal 13
  • [bugs:macosX][questions] how to send binary stream through this component to create exe, jar, zip and other files

    [bugs:macosX][questions] how to send binary stream through this component to create exe, jar, zip and other files

    [questions] 1, browser-based vpn 2, prohibit file upload, download, prohibit using the clipboard 3, only allow keyboard input 4, how to send binary stream through this component to create bin exe, jar, zip and other files

    [questions] 1、基于浏览器的vpn 2、禁止文件上传、下载、禁止使用剪切板 3、仅允许键盘输入 4、如何通过本组件发送二进制流创建exe、jar、zip等文件

    😀🤝🌹

    opened by hktalent 12
  • Media keys on Windows

    Media keys on Windows

    Not sure if I am doing something wrong, I am trying to test media keys on Windows 10.

    I have a super simple script just containing:

    keyboard.press_and_release('play/pause media')

    Then I play audio using VLC player, when I run my script I expect VLC to pause but nothing happens (no errors either).

    Any ideas?

    bug windows waiting-for-feedback 
    opened by jbardnz 12
  • Alt keys aren't detected properly

    Alt keys aren't detected properly

    As mentioned in a thread about a different issue:

    When I run this program:

    import keyboard
    def info(event):
        print (event.name + ", " + str(event.scan_code) + ", " + event.event_type)
    keyboard.hook(info)
    keyboard.wait("esc")
    

    and press left alt, I see "left alt, 56, down" as expected. When I release left alt, I see left alt, 56, up left alt, 56, down left alt, 56, up

    When I press and release right alt, I see: left alt, 56, down left alt, 56, up

    I went looking for someplace else to test my keyboard events, and found https://w3c.github.io/uievents/tools/key-event-viewer.html When I press and release left alt and then right alt in this tool, it looks like this: http://i.imgur.com/FNNKpZn.png It's not showing either problem.

    I was slightly surprised that it was reporting my numlock status in this other tool. I tried turning off numlock to see if that made any difference to my "keyboard" problem. It didn't.

    Windows 8.1 Tested on Python 2.7.13 and 3.6.0 keyboard 0.9.12

    bug windows waiting-for-feedback 
    opened by Hyphen-ated 12
  • Getting an error while using `from keyboard import mouse` in `macOS`

    Getting an error while using `from keyboard import mouse` in `macOS`

    Exception in thread Thread-2 (run):
    Traceback (most recent call last):
      File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 1016, in _bootstrap_inner
        self.run()
      File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 953, in run
        self._target(*self._args, **self._kwargs)
      File "/Users/zxff/Documents/tracker/python-scripts/.venv/lib/python3.10/site-packages/keyboard/_darwinmouse.py", line 53, in run
        Quartz.CFRunLoopRunInMode(Quartz.kCFRunLoopDefaultMode, 5, False)
      File "/Users/zxff/Documents/tracker/python-scripts/.venv/lib/python3.10/site-packages/keyboard/_darwinmouse.py", line 58, in handler
        key_name = name_from_scancode(scan_code)
    NameError: name 'name_from_scancode' is not defined
    
    opened by prashanshajain 0
  • Mac OS Ventura compatibility issue!

    Mac OS Ventura compatibility issue!

    It seem on the latest Mac OS Ventura, event.name become None and causing the keyboard library to raise Exception on all keyboard event (except for non-layout key). The exception which got raised is:

    TypeError: object of type 'NoneType' has no len()
    

    I'm looking at the source code and may be able to fix this issue soon!

    opened by tranvietanh1991 0
  • Fix write work with delay

    Fix write work with delay

    Hello! I was working on my joke project using this library and found a strange bug. The delay parameter in the write function does not work correctly on Mac OS. We don't wait every delay time before every letter input, but wait a delay before every word input.

    Issue: https://github.com/boppreh/keyboard/issues/582

    opened by DanilXO 0
  • Incorrect work with delay in write function

    Incorrect work with delay in write function

    Hello! I was working on my joke project using this library and found a strange bug. The delay parameter in the write function does not work correctly on Mac OS. We don't wait every delay time before every letter input, but wait a delay before every word input.

    This is very easy to fix. Like this:

    def write(text, delay=0, restore_state_after=True, exact=None):
        """
        ...
        """
        if exact is None:
            exact = _platform.system() == 'Windows'
    
        state = stash_state()
        
        # Window's typing of unicode characters is quite efficient and should be preferred.
        if exact:
            for letter in text:
                if letter in '\n\b':
                    send(letter)
                else:
                    _os_keyboard.type_unicode(letter)
                if delay: _time.sleep(delay)
        else:
            for letter in text:
                try:
                    entries = _os_keyboard.map_name(normalize_name(letter))
                    scan_code, modifiers = next(iter(entries))
                except (KeyError, ValueError):
                    _os_keyboard.type_unicode(letter)
                    # todo: We should add "if delay: _time.sleep(delay)" here.
                    continue
                
                for modifier in modifiers:
                    press(modifier)
    
                _os_keyboard.press(scan_code)
                _os_keyboard.release(scan_code)
    
                for modifier in modifiers:
                    release(modifier)
    
                if delay:
                    _time.sleep(delay)
    
        if restore_state_after:
            restore_modifiers(state)
    

    Should I create a PR for this?

    opened by DanilXO 1
  • Question: is there any way to get if any non specified key was pressed without blocking

    Question: is there any way to get if any non specified key was pressed without blocking

    pretty much i just need to check if any key on the keyboard without having to specify a key to check is pressed without blocking program from continuing if there is none

    while True:
        if keyboard.read_event("any key") == True):
    		print("doing thing 1")
    	else:
    		print("doing thing 2")
    

    and idk if im crazy but i cant seem to find anything that does that in the documentation

    opened by garandal245 0
Releases(v0.13.5)
  • v0.13.5(Mar 23, 2020)

  • v0.13.4(Sep 25, 2019)

  • v0.13.3(Mar 18, 2019)

    • [Windows] Fix overflow error on Python 3.7.
    • [Mac] Added alt gr -> alt mapping.
    • [Mac] Added support for right shift.
    • [All] Fixed numlock alias.
    • [All] Fixed example code.
    Source code(tar.gz)
    Source code(zip)
  • v0.13.2(May 18, 2018)

    • [Mac] Fixed "map_name" error (i.e. implement new backend API).
    • [Win] Improve detection of "right alt" key.
    • [All] Misc fixes for edge cases.
    Source code(tar.gz)
    Source code(zip)
  • v0.13.1(Mar 27, 2018)

  • v0.13.0(Mar 26, 2018)

    • [All] New remap_ and block_ functions.
    • [All] New high-level functions for parsing and converting hotkey names.
    • [All] Added .modifiers and .is_keymap attribute to events.
    • [All] Event name now matches character typed (e.g. now event from key 1 reports as ! if shift is pressed). This gives get_typed_strings more precision.
    • [Windows] New key suppression system should fix most bugs with suppress=True.
    • [Linux] Added .device attribute to events.
    • [All] Many, many bugfixes.
    Source code(tar.gz)
    Source code(zip)
  • v0.11.0(Aug 24, 2017)

    • [Windows] Used explicit WinDLL to fix "expected CFunctionType instance instead of CFunctionType".
    • [Windows] Added more Windows virtual key codes for key name mapping (should fix .e.g "?").
    • [All] Fixed canonicalization removing too much space (thanks @iliazeus).
    • [All] Added start_recording and stop_recording for more flexible macros (thanks @softuser25 for the suggestion).
    • [All] Added read_shortcut function.
    • [All] Added get_shortcut_name function.
    • [All] Cleaned up examples folder and added more examples.
    Source code(tar.gz)
    Source code(zip)
  • v0.10.4(Aug 15, 2017)

    • [Mac] Added aliases for modifiers (control->ctrl, option->alt, command->windows).
    • [All] Add reference to mouse project.
    • [All] Use WinDLL for mouse part instead of raw ctypes.windll.user32.
    Source code(tar.gz)
    Source code(zip)
  • v0.10.3(Aug 8, 2017)

  • v0.10.2(Aug 8, 2017)

    • [All] Removed ctypes type-hints to avoid runtime errors in unusual systems.
    • [All] Add mention of new mouse project.
    • [All] Add mention of experimental OS X support.
    • [All] Fixes to release process.
    Source code(tar.gz)
    Source code(zip)
  • v0.10.0(Aug 3, 2017)

    • [OS X] Added experimental OS X support (thanks @glitchassassin!).
    • [Windows] Fixed error on fractional mouse.wheel() (thanks @bobonthenet!).
    • [Windows] Fixed name for arrow keys` virtual key codes.
    • [Windows] Make backend easier to use in other projects (e.g. _winkeyboard.prepare_intercept).
    • [Linux] Fixed mouse support in Mint VirtualBox guest (thanks @foodforarabbit!).
    • [All] Added mouse alias hold = press (thanks @DanMossa!).
    • [All] Added mouse.drag.
    • [All] Added examples on how to use the library.
    • [All] Update docs to mention how to differentiate key presses and releases (thanks @TrakJohnson!).
    • [All] Change the default value of add_abbreviation(..., match_suffix).
    Source code(tar.gz)
    Source code(zip)
  • v0.9.12(Feb 4, 2017)

    • [Windows] Fixed some incorrect key names (e.g. enter as '\r', and left keys reported as 'right ...')
    • [Python2] long scan codes no longer crash the matches function.
    • [All] add read_key function, which blocks and returns the next event.
    • [All] Added makefile.
    Source code(tar.gz)
    Source code(zip)
  • v0.9.11(Feb 2, 2017)

  • v0.9.10(Jan 29, 2017)

    • [Windows] Add suppress parameter to hotkeys to block the combination from being sent to other programs.
    • [Windows] Better key mapping for common keys (now using Virtual Key Codes when possible).
    • [Windows] Normalize numpad and key code names.
    • [Linux] Errors about requiring sudo are now thrown in the main thread, making them catchable.
    • [All] wheel method in mouse module.
    Source code(tar.gz)
    Source code(zip)
  • v0.9.9(Dec 18, 2016)

    • [Windows] Include scan codes in generated events, instead of only Virtual Key Codes. This allows software like Citrix to receive the events correctly.
    • [Windows] Fix bugs that prevented keys without associated Virtual Key Codes from beign processed.
    Source code(tar.gz)
    Source code(zip)
  • v0.9.8(Dec 10, 2016)

  • v0.9.7(Nov 16, 2016)

  • v0.9.6(Nov 14, 2016)

    • [Windows] Modifier keys now report 'left' or 'right' on their names.
    • [Windows] Keypad attribute should be much more accurate even with NumLock.
    • [Windows] Media keys are now fully supported for both report and playback.
    Source code(tar.gz)
    Source code(zip)
  • v0.9.5(Nov 14, 2016)

    • [Windows] Add aliases to correct page down/page up names.
    • [Windows] Fixed a bug where left and right key events were being created without names.
    • [Windows] Prefer to report home/page up/page down/end keys as such instead of their keypad names.
    Source code(tar.gz)
    Source code(zip)
  • v0.9.4(Nov 13, 2016)

  • v0.9.3(Nov 13, 2016)

  • v0.9.2(Nov 13, 2016)

  • v0.9.1(Nov 13, 2016)

    • Add add_abbreviation and register_word_listener functions.
    • Add functions for low level hooks (hook, hook_key).
    • Add on_press and on_release functions.
    • Add alternative names (aliases) for many functions.
    • Add large number of alternative key names, especially for accents.
    • Make module produce and consume JSON if ran as script (python -m keyboard).
    • 100% test coverage.
    • [Linux] Add support for writing arbitrary Unicode.
    • [Linux] Look for Linux keyboard devices in /proc/bus/input/devices.
    • [Linux] Aggregate as many devices as possibles (e.g. USB keyboard on notebook).
    • [Linux] Improved support for internationalized keys.
    • [Windows] Process keys asynchronously to reduce key delay.
    • [All] Too many bugfixes to count.
    • [All] Major backend refactor.
    Source code(tar.gz)
    Source code(zip)
Owner
BoppreH
BoppreH
A Python class for controlling the Pimoroni RGB Keypad for Raspberry Pi Pico

rgbkeypad A Python class for controlling the Pimoroni RGB Keypad for the Raspberry Pi Pico. Compatible with MicroPython and CircuitPython. keypad = RG

Martin O'Hanlon 43 Nov 11, 2022
Automatically draw a KiCad schematic for a circuit prototyped on a breadboard.

Schematic-o-matic Schematic-o-matic automatically draws a KiCad schematic for a circuit prototyped on a breadboard. How It Works The first step in the

Nick Bild 22 Oct 11, 2022
MicroPython driver for 74HC595 shift registers

MicroPython 74HC595 A MicroPython library for 74HC595 8-bit shift registers. There's both an SPI version and a bit-bang version, each with a slightly

Mike Causer 17 Nov 29, 2022
Uses the Duke Energy Gateway to import near real time energy usage into Home Assistant

Duke Energy Gateway This is a custom integration for Home Assistant. It pulls near-real-time energy usage from Duke Energy via the Duke Energy Gateway

Michael Meli 28 Dec 23, 2022
Python script for printing to the Hanshow price-tag

This repository contains Python code for talking to the ATC_TLSR_Paper open-source firmware for the Hanshow e-paper pricetag. Installation # Clone the

12 Oct 06, 2022
A set of postprocessing scripts and macro to accelerate the gyroid infill print speed with Klipper

A set of postprocessing scripts and macro to accelerate the gyroid infill print speed with Klipper

Jérôme W. 75 Jan 07, 2023
CPU benchmark by calculating Pi, powered by Python3

cpu-benchmark Info: CPU benchmark by calculating Pi, powered by Python 3. Algorithm The program calculates pi with an accuracy of 10,000 decimal place

Alex Dedyura 20 Jan 03, 2023
A python script for macOS to enable scrolling with the 3M ergonomic mouse EM500GPS in any application.

A python script for macOS to enable scrolling with the 3M ergonomic mouse EM500GPS in any application.

3 Feb 19, 2022
Custom component for Home Assistant that integrates Candy/Haier Wi-Fi washing machines (also known as Simply-Fi).

Candy Home Assistant component Custom component for Home Assistant that integrates Candy/Haier Wi-Fi washing machines (also known as Simply-Fi). This

Olivér Falvai 61 Dec 29, 2022
Python library for the Phomemo m02s bluetooth thermal printer

Phomemo M02S Python library This is a basic Python library for controlling the Phomemo M02S bluetooth thermal printer. It probably only works on Mac &

Stargirl Flowers 28 Nov 07, 2022
ok-system-helper是一个简单的系统硬件的实时信息收集工具,使用python3.x开发

ok-system-helper ok-system-helper是一个简单的系统硬件的实时信息收集工具,使用python3.x开发,支持哪些硬件:CPU、内存、SWAP、磁盘、网卡流量。用户可在自己的项目中直接引入、开箱即用,或者结合flask等web框架轻松做成http接口供前端调用,亦可通过注

xlvchao 1 Feb 08, 2022
OPNsense integration with Home Assistant

hass-opnsense Join OPNsense with home-assistant! hass-opnsense uses the built-in xmlrpc service of OPNsense for all interactions. This project is curr

Travis Glenn Hansen 54 Jan 03, 2023
Huawei Solar sensors for Home Assistant

Huawei Solar Sensors This integration splits out the various values that are fetched from your Huawei Solar inverter into separate HomeAssistant senso

Thijs Walcarius 151 Dec 31, 2022
PyTorch implementation of paper "MT-ORL: Multi-Task Occlusion Relationship Learning" (ICCV 2021)

MT-ORL: Multi-Task Occlusion Relationship Learning Official implementation of paper "MT-ORL: Multi-Task Occlusion Relationship Learning" (ICCV 2021) P

Panhe Feng 12 Oct 11, 2022
A rubiks cube timer using a distance sensor and a raspberry pi 4, and possibly the pi pico to reduce size and cost.

distance sensor cube timer A rubiks cube timer using a distance sensor and a raspberry pi 4, and possibly the pi pico to reduce size and cost. How to

3 Feb 21, 2022
Estimation of whether or not the persons given information will have diabetes.

Diabetes Business Problem : It is desired to develop a machine learning model that can predict whether people have diabetes when their characteristics

Barış TOKATLIOĞLU 0 Jan 20, 2022
Hardware: CTWingSKIT_BC28 Development Toolkit

IoT Portal Monitor Tools hardware: CTWingSKIT_BC28 Development Toolkit serial port driver: ST-LINK hardware development environment: Keli 5 MDK IoT pl

Fengming Zhang 1 Nov 07, 2021
A battery pack simulation tool that uses the PyBaMM framework

Overview of liionpack liionpack takes a 1D PyBaMM model and makes it into a pack. You can either specify the configuration e.g. 16 cells in parallel a

PyBaMM Team 40 Jan 05, 2023
Setup DevTerm to be a cool non-GUI device

DevTerm hobby project I bought this amazing device: DevTerm A-0604. It has a beefy ARM processor, runs a custom version of Armbian, embraces Open Sour

Alex Shteinikov 9 Nov 17, 2022
Simple Weather Check base on Hefeng api, Work on raspberry Pi

Simple Weather Check base on Hefeng api, Work on raspberry Pi

Retr0mous 28 Sep 17, 2022