Skip to main content

PyHotKey

PyHotKey is a cross-platform keyboard module for Python. Based on "pynput".

Features:

  • Control keyboard.
  • Record and register hotkey.
  • "MagicKey".
  • Record keyboard history.

! Attention !

To activate all functions of this module, such as suppress hotkeys and interact with the task manager (Windows)...You MUST run your application with the highest privileges.

  • Windows: run your application as administrator.
  • Linux: run your application as root or use "sudo" command to launch your application.
  • Mac OS: same as Linux or whitelist your application: open "System Preferences -> Security & Privacy -> Privacy -> Accessibility (on the left)", click the lock to make changes (at the bottom), check your application on the right.

Install

pip install PyHotKey

Usage

Import:

from PyHotKey import Key, keyboard

Control keyboard

# Press
keyboard.press(Key.space)

# Release
keyboard.release('z')

# Tap (on_press and release)
keyboard.tap('x')

# Do something while holding down certain keys
with keyboard.pressed(Key.ctrl, Key.shift):
    do_something()

# Type a string
keyboard.type('Xpp521')

PS: If you're recording hotkey, these apis won't work.

Hotkey:

# Register a hotkey (multiple keys)
id1 = keyboard.register_hotkey([Key.ctrl_l, Key.alt_l, 'z'], None,
                               func, func_arg1, func_arg2=1)

if id1 == -1:
    print('Already registered!')
elif id1 == 0:
    print('Invalid parameters!')
else:
    print('Hotkey id: {}'.format(id1))

# Register a hotkey (single key)
# 3 means tap three times to trigger the hotkey (must >= 2)
id2 = keyboard.register_hotkey([Key.caps_lock], 3, func,
                               func_arg1, func_arg2, func_arg3=233)

# Unregister hotkey by keys
r1 = keyboard.unregister_hotkey_by_keys([Key.ctrl_l, Key.alt_l, 'z'])
r2 = keyboard.unregister_hotkey_by_keys([Key.caps_lock], 2)

# Unregister hotkey by hotkey id
r3 = keyboard.unregister_hotkey_by_id(id2)

# Unregister all hotkeys
keyboard.unregister_all_hotkeys()

# Print all hotkeys
print(keyboard.hotkeys)

# Suppress the last key after triggering a hotkey
# With this api, you can even override system hotkeys
# PS1: Require the highest privileges
# PS2: Currently doesn't work in Linux
keyboard.suppress_hotkey = True

# ttl: time to live (for hotkeys with multiple keys)
# When a key is pressed for more than "ttl" seconds,
# it will be ignored in the next key on_press/release event.
keyboard.ttl = 7

# Interval: the max interval time between each tap
# (for hotkeys with single key)
keyboard.interval = 0.5

Record hotkey:

# The callback function for recording hotkey
# Use "key_list" to register hotkey later
def callback(key_list):
    print(key_list)

# Start recording a hotkey (multiple keys)
keyboard.start_recording_hotkey_multiple(callback)

# Start recording a hotkey (single key)
keyboard.start_recording_hotkey_single(callback)

# Stop recording hotkey
keyboard.stop_recording_hotkey()

# Print recording state
print(keyboard.recording_state)

PS: Check the example: Recording.py.

MagicKey

MagicKey can change the behaviour of a single key:

  • trigger functions for pressed and released event.
  • Suppress the original function.
# Set a magickey to trigger when "ctrl" is pressed (suppress)
r1 = keyboard.set_magickey_on_press(Key.ctrl_l, func,
                                  func_arg1, func_arg2=233)

# Set a magickey to trigger when "x" is released (don't suppress)
r2 = keyboard.set_magickey_on_release('x', func,
                                    func_arg1, func_arg2='Xpp')

# Remove the magickey triggered when x is pressed
r3 = keyboard.remove_magickey_on_press('x')

# Remove the magickey triggered when x is pressed or released
r3 = keyboard.remove_magickey('x')

# Remove all magickeys
r5 = keyboard.remove_all_magickeys()

# Print all magickeys
print(keyboard.magickeys)

# Suppress the single key after triggering a magickey
# Use this api to change the function of a single key
# PS1: Require the highest privileges
# PS2: Currently doesn't work in Linux
# PS3: May cause unknown bugs, be careful
keybord.suppress_magickey = True

PS: Check the example: magickey.py.

Other APIs

# Print the currently pressed keys
print(keyboard.pressed_keys)

# Check whether a key is pressed
if 'z' in keyboard.pressed_keys:
    print("'z' is pressed")

Toggle Listener

# Print keyboard listener's running state
print(keyboard.listener_running)

# Stop keyboard listener
# When stopped, hotkey and magickey related functions won't work
keyboard.stop_listener()

# Start keyboard listener
# You can restart the listener after stopping it
keyboard.start_listener()

PS: Generally, you may not use these apis.

Logger:

There is a classic logger by default, you can also set a custom logger.

# Turn on the logger
keyboard.toggle_logger(1)

# Get the current logger
logger = keyboard.logger

# Add a file handler to the default logger
from logging import FileHandler
keyboard.logger.addHandler(FileHandler('Keyboard History.txt', 'a', 'utf-8'))

# Set a custom logger
# PS: The custom logger must have the following method:
# 'trace', 'debug', 'info', 'success', 'log',
# 'warning', 'error', 'critical', 'exception'
from loguru import logger
r = keyboard.set_logger(logger)

Release Note

v1.5.2

  • [Fix] some hotkey can't be recorded.
  • [Change] Hotkeys with single keystroke won't be triggered if the tapping is interrupted.
  • [Change] Rename several apis.
  • [Change] Rebuild logging function.
  • [Remove] "strict mode".

v1.5.0

  • [+] Wetkey: triggered when a single key is pressed or released.
  • [+] Suppress: Suppress the last key after triggering a hotkey.

v1.4.1

  • Add api: "unregister_all_hotkeys".
  • Change the parameter order of "register_hotkey".
  • Now you can use "pressed_keys" to check whether a key is pressed.

v1.4.0 - 2022 Reborn

After 3 years I'm back with the new "PyHotKey".

Changes:

  • Fixed a lot of bugs.
  • Now you can record hotkey and control keyboard.
  • Real cross platform this time.
  • And more convenient apis...

Check "README.md".


v1.3.3

Bug Fixes

  • Combination hot key: Fix the keystroke value error of combination hot key.

Refactor

  • Simplify README.md.

v1.3.2

Bug Fixes

  • Log path: fix the default log path overwrites the custom log path when setting "manager.logger = True".

Refactor

  • Adjust code structure.
  • Rewrite README.md.

v1.3.1

  • Delete a deprecated class.
  • Replace root logger with a separate logger.
  • Rename property "hot_keys" to "hotKeyList".
  • Change documents and some code comments.

v1.3.0

  • Currently, users can customize the log path.
  • Optimize code.

v1.2.0

  • Add logger.
  • Optimize code.
  • Attempt to fix a potential bug.

v1.1.1

  • Remove log message.

v1.1.0

  • Currently, the trigger function supports arguments.
  • No longer need to call manager.start() manually.
  • Fix multiple type hot key bug.

v1.0

  • The first version.

Release files for PyHotKey 1.5.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for PyHotKey 1.5.2
File Size Uploaded
PyHotKey-1.5.2.tar.gz 18.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for PyHotKey 1.5.2
File Interpreter ABI Platform
PyHotKey-1.5.2-py3-none-any.whl Python 3 none any Details

Total release size: 37.9 kB

Release files / PyHotKey-1.5.2.tar.gz

Download URL PyHotKey-1.5.2.tar.gz
Size 18.0 kB
Tags Source
SHA-256 checksum
How to use checksums
39b579c038e7850c26aa67cc1f917d5546c9d973ce60ab991fd386a1d49d1ab4
BLAKE2b-256 checksum
How to use checksums
5d0bf61560ed6cb554b5973b1902419adf616ed678781e40d7c0de2f4600593f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.1.0 CPython/3.11.9

Release files / PyHotKey-1.5.2-py3-none-any.whl

Download URL PyHotKey-1.5.2-py3-none-any.whl
Size 19.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9a353ac6cd8385038dcf7142df10cf113f8541bc3128e8349b08b051f79d9983
BLAKE2b-256 checksum
How to use checksums
4ef39033d43dce32e075430a78d2c2d96fb1f81b16159f459723e3e5f818c3fb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.1.0 CPython/3.11.9

Release history Release notifications | RSS feed

This release

1.5.2 This release

2 release files

1.5.1

2 release files

1.5.0

2 release files

1.4.1

2 release files

1.4.0

2 release files

1.3.3

2 release files

1.3.2

2 release files

1.3.1

2 release files

1.3.0

2 release files

1.2.0

2 release files

1.1.1

2 release files

1.1.0

2 release files

1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page