Skip to main content

A cross-platform keyboard module.

Project description

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

MagicKey

MagicKey can change the behaviour of a single key:

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

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

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

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

# Remove all wetkeys
r5 = keyboard.remove_all_wetkeys()

# Print all wetkeys
print(keyboard.wetkeys)

# Suppress the single key after triggering a wetkey
# 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_wetkey = True

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 wetkey 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.1

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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

PyHotKey-1.5.1.tar.gz (18.0 kB view details)

Uploaded Source

Built Distribution

PyHotKey-1.5.1-py3-none-any.whl (19.9 kB view details)

Uploaded Python 3

File details

Details for the file PyHotKey-1.5.1.tar.gz.

File metadata

  • Download URL: PyHotKey-1.5.1.tar.gz
  • Upload date:
  • Size: 18.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.0 CPython/3.11.9

File hashes

Hashes for PyHotKey-1.5.1.tar.gz
Algorithm Hash digest
SHA256 bd22f3006c9a279db89cb365e0ae5bfffd4526c4c1305a2fe4818e552cda1ca5
MD5 bfa73fd963917ad804b36721d01c8e0a
BLAKE2b-256 22ead9efbf41e5a5314a4f4a8c97c6bfb456a283eb926aa5c51ec14ed0b03009

See more details on using hashes here.

File details

Details for the file PyHotKey-1.5.1-py3-none-any.whl.

File metadata

  • Download URL: PyHotKey-1.5.1-py3-none-any.whl
  • Upload date:
  • Size: 19.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.0 CPython/3.11.9

File hashes

Hashes for PyHotKey-1.5.1-py3-none-any.whl
Algorithm Hash digest
SHA256 fde99f89dce57fae65f5a39c9415a655140d0d8ab02c0498ff2c8cc63452b371
MD5 19b12083eac095474240d98eb36ba4b2
BLAKE2b-256 1506c9a0fd250ce836688c97ab05f2530eceb5a2329bf5edaab6c5d0768a8fde

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page