Как установить keyboard python

от admin

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

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

Как установить keyboard python

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

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

Установил модуль «keyboard», а python его не видит [закрыт]

Удаление модуля и последующая его переустановка.

keyboard
Release 0.13.5

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

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

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

or download and extract the zip into your project folder.

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

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

Table of Contents

keyboard.KEY_DOWN

keyboard.KEY_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)

keyboard.all_modifiers

keyboard.sided_modifiers

keyboard.version

keyboard.is_modifier(key)

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

keyboard.key_to_scan_codes(key, error_if_missing=True)

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

keyboard.parse_hotkey(hotkey)

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.

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

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.

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

keyboard.press(hotkey)

Presses and holds down a hotkey (see send ).

keyboard.release(hotkey)

Releases a hotkey (see send ).

keyboard.is_pressed(hotkey)

Returns True if the key is pressed.

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

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

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)

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

keyboard.on_release(callback, suppress=False)

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

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

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)

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

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

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

keyboard.unhook(remove)

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

keyboard.unhook_all()

Removes all keyboard hooks in use, including hotkeys, abbreviations, word listeners, record ers and wait s.

keyboard.block_key(key)

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

keyboard.remap_key(src, dst)

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

keyboard.parse_hotkey_combinations(hotkey)

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)

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 .

keyboard.remove_hotkey(hotkey_or_callback)

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

keyboard.unhook_all_hotkeys()

Removes all keyboard hotkeys in use, including abbreviations, word listeners, record ers and wait s.

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

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

keyboard.stash_state()

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)

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)

Like restore_state , but only restores modifier keys.

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

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)

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

keyboard.get_hotkey_name(names=None)

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 «+».

keyboard.read_event(suppress=False)

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

keyboard.read_key(suppress=False)

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

keyboard.read_hotkey(suppress=True)

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.

keyboard.get_typed_strings(events, allow_backspace=True)

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.

keyboard.start_recording(recorded_events_queue=None)

Starts recording all keyboard events into a global variable, or the given queue if any. Returns the queue of events and the hooked function.

keyboard.stop_recording()

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

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

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)

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)

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)

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)

Registers a hotkey that replaces one typed text with another. For example

Replaces every «tm» followed by a space with a ™ symbol (and no space). The replacement is done by sending backspace events.

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

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

Name already in use

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

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

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

or download and extract the zip into your project folder.

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

Use as standalone module:

  • 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

Waiting for a key press one time

Repeatedly waiting for a key press

Invoking code when an event happens

‘Press any key to continue’

Читать:
Как найти среднее арифметическое отрицательных чисел

Table of Contents

keyboard.KEY_DOWN

keyboard.KEY_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)

keyboard.all_modifiers

keyboard.sided_modifiers

keyboard.version

keyboard.is_modifier(key)

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

keyboard.key_to_scan_codes(key, error_if_missing=True)

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

keyboard.parse_hotkey(hotkey)

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.

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

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.

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

keyboard.press(hotkey)

Presses and holds down a hotkey (see send ).

keyboard.release(hotkey)

Releases a hotkey (see send ).

keyboard.is_pressed(hotkey)

Returns True if the key is pressed.

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

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

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)

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

keyboard.on_release(callback, suppress=False)

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

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

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)

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

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

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

keyboard.unhook(remove)

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

keyboard.unhook_all()

Removes all keyboard hooks in use, including hotkeys, abbreviations, word listeners, record ers and wait s.

keyboard.block_key(key)

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

keyboard.remap_key(src, dst)

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

keyboard.parse_hotkey_combinations(hotkey)

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)

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 .

keyboard.remove_hotkey(hotkey_or_callback)

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

keyboard.unhook_all_hotkeys()

Removes all keyboard hotkeys in use, including abbreviations, word listeners, record ers and wait s.

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

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

keyboard.stash_state()

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)

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)

Like restore_state , but only restores modifier keys.

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

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)

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

keyboard.get_hotkey_name(names=None)

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 «+».

keyboard.read_event(suppress=False)

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

keyboard.read_key(suppress=False)

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

keyboard.read_hotkey(suppress=True)

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.

keyboard.get_typed_strings(events, allow_backspace=True)

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.

keyboard.start_recording(recorded_events_queue=None)

Starts recording all keyboard events into a global variable, or the given queue if any. Returns the queue of events and the hooked function.

keyboard.stop_recording()

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

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

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)

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)

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)

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)

Registers a hotkey that replaces one typed text with another. For example

Replaces every «tm» followed by a space with a ™ symbol (and no space). The replacement is done by sending backspace events.

Guide to Python's keyboard Module

Python is one of the most suitable languages for automating tasks. Whether it's repeatable (ethical) web scraping after some time period, starting some programs on a computer start up, or automating sending mundane e-mails, Python has a lot of modules that make your life easier.

One of these is a module called keyboard , and it takes full control of your keyboard. With this module, you can type out anything, create hot-keys, create abbreviations, block the keyboard, wait for input, etc.

In this guide, we'll take a look at how to set up and use the keyboard module in Python.

Note: Applications working with automating human-like processes should be developed ethically and responsibly. The keyboard module is made to be very observable, and thus makes it both discouraged and transparent if anyone's using it to create keyloggers or malicious bots.

Installing the keyboard Module

Note: The version of Python used in this guide is 3.8. However, the keyboard module can work with both Python 2.x and Python 3.x.

If you're using Linnux, in order to use this library, you must install it as root . If you don't, you'll get an:

Also, when running your script, you should run it with root privileges:

On Windows and MacOS, as the privileges work much differently — you can install it simply via pip and run the scripts:

Note: For MacOS, you might have to allow the Terminal or other apps to change the state of your machine, such as by typing. Also keep in mind that as of September 2021, the library is still experimental on MacOS.

The keyboard Module's Functions

There are a lot of functions in this module that can be used to simulate keyboard actions.

  • keyboard.write(message, [delay]) — writes a message, with or without a delay.
  • keyboard.wait(key) — blocks the program until the key is pressed. The key is passed as a string ('space', 'esc', etc.)
  • keyboard.press(key) — presses a key and holds until the release(key) function is called.
  • keyboard.release(key) — releases a key.
  • keyboard.send(key) — presses and releases a key.
  • keyboard.add_hotkey(hotkey, function) — creates a hotkey which when pressed, executes a function .
  • keyboard.record(key) — records keyboard activity until key is pressed.
  • keyboard.play(recorded_events, [speed_factor]) — replays events recorded with keyboard.record(key) function, with an optional speed_factor .

We'll go through all of these, though, here's a quick example:

The Hello message appears on the screen, in the terminal, as if you've written it. You can automate a command very easily, and create a hotkey alias for it. Here's a (crude) example of exiting the Python REPL, writing a curl commmand and executing it:

keyboard's write() and wait() Functions

The write() command writes a message, as we've seen before, with an optional delay in the start. If no delay is set, writing is instant. It's very nicely combined with the wait() function, which awaits a certain key to be pressed.

For instance, we can create a make-shift macro, tied to, say 1 , which responds to that input with a new message. Note that there's an actual way to create hotkeys instead of this, which we'll cover later.

We'll create an infinite True loop to check for the key being pressed, and you can run the script in the background:

Note: Special characters are not supported by this function, so if you add, say, ! — you'll get hit with a StopIteration exception.

keyboard's press(), release() Functions

Since it's hard to simulate press() and release() so that the actions are visible, we'll also see record() and play() in action.

The press() function presses a key and releases it when you call release() on the same key. Note that you can't sleep() for some time to simulate holding down a key:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

However, you can hold down some special keys, such as [SHIFT] or [CTRL] this way:

keyboard's record() and play() Functions

It's not always about inputting new keys in — sometimes, you'd like to record what's going on and play it back. Keep in mind that you'll need administrator privileges to record any input like this, as the technology can easily be used to create key loggers.

The record() function accepts a trigger key, until which it records, and returns a sequence of events of type KeyboardEvent . You can then chuck this sequence of events into the play() function, which faithfully replays them, with an optional speed_factor argument that acts as a multiplier for the speed of the original events:

If we're to print the recorded_events , they'd look something like:

The effects of these methods are best seen as a gif or recreated on your machine. For instance, a sequence of writing a message, deleting it and writing a different one instead:

keyboard's send() function

The send() function encompasses press() and release() together, and is used for single keys, unlike write() which is used for entire sentences:

Once s is pressed, the w and a keys are replayed.

The press() function can also accept combinations of pressed keys. You can send a combination of "ctrl+shift+s" for instance and the dialogue for saving a file should pop up, if you're in an application that supports that operation:

Though, this isn't the right way to add hotkeys. Rather, you can use the add_hotkey() function.

keyboard's add_abbreviation() Function

The add_abbreviation() function is a pretty nifty one, as it allows you to define abbreviations for long inputs, and replaces the abbreviated versions with the saved full versions.

For instance, similar to how services like Google save your email for most input forms, you can create your own abbreviation and trigger it via [SPACE] :

While running, if you type @ followed by a [SPACE] — the long-form input will replace the typed @ .

keyboard's add_hotkey() Function

The add_hotkey() function accepts a hotkey you'd like to save, or a combination of keys, and a function. It's easy to pass in anonymous lambda functions here, though you can also add named functions.

For instance, let's add a hotkey for CTRL+j , which triggers a lambda function that logs this:

The hotkey, ctrl+alt+p , is saved and when you press this combination, you should see the output of the lambda.

Conclusion

The keyboard module is a lightweight and simple library used for simulating keystrokes and simple automation in Python. It's not very feature-rich, but can be used to automate some of the tasks you might be performing in your day-to-day work, or simply for a bit of fun.

A more mature, powerful module that can be used as an alternative is pynput.

Похожие статьи