### Complete Example with Async Robot Control Source: https://context7.com/ollipal/sshkeyboard/llms.txt A comprehensive example demonstrating real-world usage of sshkeyboard with asynchronous operations, state management, and error handling. It controls a simulated robot's speed using keyboard input and includes graceful shutdown. ```python import asyncio from sshkeyboard import listen_keyboard, stop_listening class RobotController: def __init__(self): self.speed = 0 self.running = True async def on_press(self, key): try: if key == "up": self.speed = min(100, self.speed + 10) print(f"Speed increased to {self.speed}") elif key == "down": self.speed = max(0, self.speed - 10) print(f"Speed decreased to {self.speed}") elif key == "space": self.speed = 0 print("Emergency stop!") elif key == "q": print("Quitting...") stop_listening() else: print(f"Unknown key: {key}") # Simulate sending command to robot await self.send_command() except Exception as e: print(f"Error handling key press: {e}") stop_listening() async def send_command(self): # Simulate async I/O operation await asyncio.sleep(0.1) if self.speed > 0: print(f"→ Robot moving at speed {self.speed}") # Usage controller = RobotController() print("Robot Controller Started") print("UP/DOWN: adjust speed, SPACE: stop, Q: quit, ESC: exit") listen_keyboard(on_press=controller.on_press) print("Robot Controller Stopped") ``` -------------------------------- ### Install sshkeyboard dependency Source: https://github.com/ollipal/sshkeyboard/blob/main/README.md The command to install the sshkeyboard library via pip. ```shell pip install sshkeyboard ``` -------------------------------- ### Cloning and Setting Up sshkeyboard Project Locally (Shell) Source: https://github.com/ollipal/sshkeyboard/blob/main/README.md Provides instructions for cloning the sshkeyboard repository and setting up a local development environment. This includes steps for creating and activating a virtual environment and installing development dependencies. ```shell git clone git@github.com:ollipal/sshkeyboard.git cd sshkeyboard # Optional: Create and activate virtual environment python -m venv .env source .env/bin/activate # Install development dependencies pip install -r dev-requirements.txt ``` -------------------------------- ### Listen for keyboard events in Python Source: https://github.com/ollipal/sshkeyboard/blob/main/README.md Basic implementation of keyboard event listeners. Defines press and release callback functions and starts the listener loop. ```python from sshkeyboard import listen_keyboard def press(key): print(f"'{key}' pressed") def release(key): print(f"'{key}' released") listen_keyboard( on_press=press, on_release=release, ) ``` -------------------------------- ### Sequential Mode Source: https://context7.com/ollipal/sshkeyboard/llms.txt Force callback functions to execute sequentially, ensuring that one callback completes before the next one starts. This is useful for preventing race conditions or managing resource-intensive operations. ```APIDOC ## listen_keyboard with sequential callbacks ### Description Enables sequential execution of callbacks using the `sequential=True` parameter. This ensures callbacks are processed one after another, unlike the default concurrent execution. ### Method `listen_keyboard(on_press=press, sequential=True)` ### Parameters - **sequential** (bool) - Set to `True` to enforce sequential execution of callbacks. ### Request Example ```python import time from sshkeyboard import listen_keyboard def press(key): print(f"'{key}' pressed") time.sleep(3) # Simulate a long-running task print(f"'{key}' slept") # Default (concurrent) - pressing 'a', 's', 'd' quickly: # 'a' pressed # 's' pressed # 'd' pressed # 'a' slept # 's' slept # 'd' slept # With sequential=True - pressing 'a', 's', 'd' quickly: listen_keyboard(on_press=press, sequential=True) # 'a' pressed # 'a' slept # 's' pressed # 's' slept # 'd' pressed # 'd' slept ``` ### Response #### Success Response (None) No direct return value. Modifies the callback execution order. #### Response Example None ``` -------------------------------- ### Building Documentation Locally for sshkeyboard (Shell) Source: https://github.com/ollipal/sshkeyboard/blob/main/README.md Details the process of building the project's documentation locally using Sphinx. It includes navigating to the docs directory, running the build command, and instructions for enabling live reloading during documentation development. ```shell # Navigate to the docs directory cd docs # Build the documentation make html # To force a rebuild (if needed) # rm -rf build/ && make html # For live automatic rebuilding during development # sphinx-autobuild ./source/ ./build/html/ ``` -------------------------------- ### Manual Asyncio Event Loop Control (Python) Source: https://context7.com/ollipal/sshkeyboard/llms.txt Demonstrates using `listen_keyboard_manual` for scenarios requiring explicit control over the asyncio event loop, typically used within an existing `asyncio.run()` context. ```python import asyncio from sshkeyboard import listen_keyboard_manual async def press(key): print(f"'{key}' pressed") async def release(key): print(f"'{key}' released") # Manual asyncio control asyncio.run(listen_keyboard_manual(on_press=press, on_release=release)) # This is equivalent to: # listen_keyboard(on_press=press, on_release=release) ``` -------------------------------- ### Mixed Async and Sync Callbacks (Python) Source: https://context7.com/ollipal/sshkeyboard/llms.txt Shows how to combine both asynchronous (`async def`) and synchronous (regular `def`) callback functions within a single `listen_keyboard` call, illustrating behavior in both concurrent (default) and sequential modes. ```python import asyncio import time from sshkeyboard import listen_keyboard async def press(key): print(f"'{key}' pressed") await asyncio.sleep(3) print(f"'{key}' press slept") def release(key): print(f"'{key}' released") time.sleep(3) print(f"'{key}' release slept") # Concurrent mode (default) listen_keyboard(on_press=press, on_release=release) # Pressing 'a', 's' outputs: # 'a' pressed # 'a' released # 's' pressed # 's' released # 'a' press slept # 's' press slept # 'a' release slept # 's' release slept # Sequential mode listen_keyboard(on_press=press, on_release=release, sequential=True) # Pressing 'a', 's' outputs: # 'a' pressed # 'a' press slept # 'a' released # 'a' release slept # 's' pressed # 's' press slept # 's' released # 's' release slept ``` -------------------------------- ### Basic Keyboard Listening with Callbacks (Python) Source: https://context7.com/ollipal/sshkeyboard/llms.txt Demonstrates how to use `listen_keyboard` to capture key press and release events using specified callback functions. The listener stops by default when the 'esc' key is pressed. ```python from sshkeyboard import listen_keyboard def press(key): print(f"'{key}' pressed") def release(key): print(f"'{key}' released") # Listen until 'esc' is pressed (default) listen_keyboard( on_press=press, on_release=release, ) # Output when pressing 'a': # 'a' pressed # 'a' released ``` -------------------------------- ### Mixing Async and Concurrent Callbacks with sshkeyboard (Python) Source: https://github.com/ollipal/sshkeyboard/blob/main/README.md Demonstrates how to use both asynchronous (async) and synchronous (blocking) callbacks for key press and release events. It highlights the different execution orders based on the `sequential` parameter. Note that async callbacks should use `asyncio.sleep` instead of `time.sleep`. ```python import asyncio import time from sshkeyboard import listen_keyboard async def press(key): print(f"'{key}' pressed") await asyncio.sleep(3) print(f"'{key}' press slept") def release(key): print(f"'{key}' relased") time.sleep(3) print(f"'{key}' release slept") # Example usage without sequential=True # listen_keyboard( # on_press=press, # on_release=release, # ) # Example usage with sequential=True listen_keyboard( on_press=press, on_release=release, sequential=True, ) ``` -------------------------------- ### Control keyboard callback execution mode Source: https://github.com/ollipal/sshkeyboard/blob/main/README.md Demonstrates the use of sequential mode to ensure callbacks execute one after another without overlap, instead of the default concurrent behavior. ```python import time from sshkeyboard import listen_keyboard def press(key): print(f"'{key}' pressed") time.sleep(3) print(f"'{key}' slept") listen_keyboard( on_press=press, sequential=True, ) ``` -------------------------------- ### Use asynchronous callbacks with asyncio Source: https://github.com/ollipal/sshkeyboard/blob/main/README.md Shows how to integrate asyncio coroutines as keyboard event callbacks, ensuring non-blocking operations with await. ```python import asyncio from sshkeyboard import listen_keyboard async def press(key): print(f"'{key}' pressed") await asyncio.sleep(3) print(f"'{key}' slept") listen_keyboard(on_press=press) ``` -------------------------------- ### Tuning sshkeyboard Timing Parameters (Python) Source: https://github.com/ollipal/sshkeyboard/blob/main/README.md Explains how to adjust the timing parameters `delay_second_char` and `delay_other_chars` in `listen_keyboard`. These parameters can help resolve issues where multiple callbacks are triggered for a single key press or when key releases are too slow. ```python from sshkeyboard import listen_keyboard def my_callback(key): print(f"Key: {key}") listen_keyboard( on_press=my_callback, delay_second_char=0.75, # Adjusts delay for the second character in a sequence delay_other_chars=0.05, # Adjusts delay for subsequent characters ) ``` -------------------------------- ### Mixed Async and Sync Callbacks Source: https://context7.com/ollipal/sshkeyboard/llms.txt Combine both asynchronous and synchronous callback functions within the same `listen_keyboard` call. The library handles the execution appropriately based on the callback type. ```APIDOC ## listen_keyboard with mixed async and sync callbacks ### Description Allows using both asynchronous and synchronous callback functions simultaneously. The execution mode (concurrent or sequential) affects how these mixed callbacks are handled. ### Method `listen_keyboard(on_press=async_press, on_release=sync_release, sequential=True)` ### Parameters - **on_press** (async callable) - Asynchronous function for key press. - **on_release** (callable) - Synchronous function for key release. - **sequential** (bool) - Determines if callbacks execute sequentially (`True`) or concurrently (`False`). ### Request Example ```python import asyncio import time from sshkeyboard import listen_keyboard async def press(key): print(f"'{key}' pressed") await asyncio.sleep(3) print(f"'{key}' press slept") def release(key): print(f"'{key}' released") time.sleep(3) print(f"'{key}' release slept") # Concurrent mode (default) listen_keyboard(on_press=press, on_release=release) # Pressing 'a', 's' outputs: # 'a' pressed # 'a' released # 's' pressed # 's' released # 'a' press slept # 's' press slept # 'a' release slept # 's' release slept # Sequential mode listen_keyboard(on_press=press, on_release=release, sequential=True) # Pressing 'a', 's' outputs: # 'a' pressed # 'a' press slept # 'a' released # 'a' release slept # 's' pressed # 's' press slept # 's' released # 's' release slept ``` ### Response #### Success Response (None) No direct return value. Enables mixed callback execution. #### Response Example None ``` -------------------------------- ### Manual Asyncio Control Source: https://context7.com/ollipal/sshkeyboard/llms.txt Use `listen_keyboard_manual()` for explicit control over the asyncio event loop. This is suitable for integrating `sshkeyboard` into existing asyncio applications. ```APIDOC ## listen_keyboard_manual ### Description Provides manual control over the asyncio event loop for keyboard listening. It returns an asyncio task that can be managed within your event loop. ### Method `listen_keyboard_manual(on_press=None, on_release=None, until='esc', sequential=False, debug=False)` ### Parameters - **on_press** (async callable) - Async function for key press events. - **on_release** (async callable) - Async function for key release events. - **until** (str or None) - Key to stop listening. - **sequential** (bool) - Whether callbacks should run sequentially. - **debug** (bool) - Enable debug logging. ### Request Example ```python import asyncio from sshkeyboard import listen_keyboard_manual async def press(key): print(f"'{key}' pressed") async def release(key): print(f"'{key}' released") async def main(): # Run the manual listener within the event loop await listen_keyboard_manual(on_press=press, on_release=release) if __name__ == "__main__": asyncio.run(main()) # This is functionally equivalent to: # listen_keyboard(on_press=press, on_release=release) ``` ### Response #### Success Response (asyncio.Task) Returns an asyncio Task object representing the keyboard listener. #### Response Example `# An asyncio.Task object` ``` -------------------------------- ### Asynchronous Keyboard Callbacks (Python) Source: https://context7.com/ollipal/sshkeyboard/llms.txt Demonstrates using asynchronous functions (`async def`) as callbacks with `listen_keyboard`. This allows for non-blocking operations within callbacks, using `asyncio.sleep` instead of `time.sleep`. ```python import asyncio from sshkeyboard import listen_keyboard async def press(key): print(f"'{key}' pressed") await asyncio.sleep(3) # Use await asyncio.sleep, NOT time.sleep print(f"'{key}' slept") def release(key): print(f"'{key}' released") # Supports async callbacks (handles event loop automatically) listen_keyboard(on_press=press, on_release=release) ``` -------------------------------- ### Enabling Debug Mode in sshkeyboard (Python) Source: https://github.com/ollipal/sshkeyboard/blob/main/README.md Illustrates how to activate debug mode in the `listen_keyboard` function. When enabled, it provides additional logs for skipped keys, which can be helpful for troubleshooting registration issues. ```python from sshkeyboard import listen_keyboard def my_callback(key): print(f"Key: {key}") listen_keyboard( on_press=my_callback, debug=True, ) ``` -------------------------------- ### Customizing the Stop Key for Keyboard Listening (Python) Source: https://context7.com/ollipal/sshkeyboard/llms.txt Shows how to modify the `listen_keyboard` function to stop listening based on a different key press than the default 'esc', or to listen indefinitely. ```python from sshkeyboard import listen_keyboard def press(key): print(f"'{key}' pressed") # Listen until 'space' is pressed instead of 'esc' listen_keyboard( on_press=press, until="space", ) # Listen indefinitely (only stop_listening() or errors will stop it) listen_keyboard( on_press=press, until=None, ) ``` -------------------------------- ### Basic Keyboard Listening Source: https://context7.com/ollipal/sshkeyboard/llms.txt Listen for keyboard press and release events using callback functions. The listener stops by default when the 'esc' key is pressed. ```APIDOC ## listen_keyboard ### Description Listens for keyboard press and release events and calls the provided callback functions. ### Method `listen_keyboard(on_press=None, on_release=None, until='esc', sequential=False, debug=False)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **on_press** (callable) - Optional - Function to call when a key is pressed. - **on_release** (callable) - Optional - Function to call when a key is released. - **until** (str or None) - Optional - The key that will stop the listener. Defaults to 'esc'. If None, the listener will run indefinitely until stopped programmatically or by an error. - **sequential** (bool) - Optional - If True, callbacks will execute one by one. Defaults to False (concurrent execution). - **debug** (bool) - Optional - If True, prints logs for skipped or non-supported keys. Defaults to False. ### Request Example ```python from sshkeyboard import listen_keyboard def press(key): print(f"'{key}' pressed") def release(key): print(f"'{key}' released") listen_keyboard(on_press=press, on_release=release) ``` ### Response #### Success Response (None) This function does not return a value. It runs until the `until` key is pressed or `stop_listening()` is called. #### Response Example None ``` -------------------------------- ### Debug Mode Source: https://context7.com/ollipal/sshkeyboard/llms.txt Enable debug mode to receive detailed logs about key events, including information about keys that were skipped or are not supported by the library. ```APIDOC ## listen_keyboard with debug mode ### Description Activates debug logging for the keyboard listener. This is helpful for troubleshooting and understanding which keys are being detected or ignored. ### Method `listen_keyboard(on_press=press, debug=True)` ### Parameters - **debug** (bool) - Set to `True` to enable debug messages. ### Request Example ```python from sshkeyboard import listen_keyboard def press(key): print(f"'{key}' pressed") # Enable debug mode listen_keyboard(on_press=press, debug=True) # Example output with debug=True when an unsupported key is pressed: # Debug: Key 'f13' skipped (not supported) ``` ### Response #### Success Response (None) No direct return value. Enables debug logging output to the console. #### Response Example None ``` -------------------------------- ### Debug Mode for Keyboard Events (Python) Source: https://context7.com/ollipal/sshkeyboard/llms.txt Enables debug mode in `listen_keyboard` to log information about keys that are skipped or not supported by the library, aiding in troubleshooting. ```python from sshkeyboard import listen_keyboard def press(key): print(f"'{key}' pressed") # To enable debug mode, you would typically pass a debug=True argument # if the function supported it directly, or configure logging. # Example assuming a hypothetical 'debug' parameter: # listen_keyboard(on_press=press, debug=True) # Note: The provided text does not show the exact syntax for enabling debug mode, # but the description indicates its purpose. # Actual implementation might involve setting up Python's logging module # or a specific debug flag if available in the library's final API. ``` -------------------------------- ### Enable Debug Mode for Key Registration Source: https://context7.com/ollipal/sshkeyboard/llms.txt Enables debug mode in the sshkeyboard library to help troubleshoot issues related to key registration. This mode prints messages indicating unsupported ANSI or Windows characters encountered during input. ```python from sshkeyboard import listen_keyboard def press(key): print(f"'{key}' pressed") # Enable debug mode listen_keyboard( on_press=press, debug=True, ) ``` -------------------------------- ### Configure Thread Pool Size for Callbacks Source: https://context7.com/ollipal/sshkeyboard/llms.txt Allows configuration of the thread pool size for executing callbacks concurrently. Set `max_thread_pool_workers` to a specific number to manage the number of parallel operations. This setting is ignored if `sequential=True`. ```python import time from sshkeyboard import listen_keyboard def press(key): print(f"'{key}' pressed") # Some time-consuming operation time.sleep(1) # Use custom thread pool size for concurrent callbacks listen_keyboard( on_press=press, max_thread_pool_workers=4, # Default: None (uses Python's default) ) ``` -------------------------------- ### Programmatic Stop of Keyboard Listener (Python) Source: https://context7.com/ollipal/sshkeyboard/llms.txt Illustrates how to programmatically stop the keyboard listener from within a callback function or external code using the `stop_listening()` function. ```python from sshkeyboard import listen_keyboard, stop_listening def press(key): print(f"'{key}' pressed") if key == "z": print("Stopping listener...") stop_listening() listen_keyboard(on_press=press) # Output: # 'a' pressed # 'b' pressed # 'z' pressed # Stopping listener... ``` -------------------------------- ### Async Callbacks Source: https://context7.com/ollipal/sshkeyboard/llms.txt Utilize asynchronous callback functions for non-blocking operations. `sshkeyboard` automatically manages the asyncio event loop when async callbacks are provided. ```APIDOC ## listen_keyboard with async callbacks ### Description Supports asynchronous functions as callbacks for `on_press` and `on_release`. The library handles the asyncio event loop automatically. ### Method `listen_keyboard(on_press=async_press, on_release=async_release)` ### Parameters - **on_press** (async callable) - An asynchronous function to execute when a key is pressed. - **on_release** (async callable) - An asynchronous function to execute when a key is released. ### Request Example ```python import asyncio from sshkeyboard import listen_keyboard async def press(key): print(f"'{key}' pressed") await asyncio.sleep(3) # Use await asyncio.sleep for async operations print(f"'{key}' slept") def release(key): # Sync callbacks are also supported print(f"'{key}' released") listen_keyboard(on_press=press, on_release=release) ``` ### Response #### Success Response (None) No direct return value. Enables asynchronous callback execution. #### Response Example None ``` -------------------------------- ### Stopping sshkeyboard Listener with 'until' or stop_listening() (Python) Source: https://github.com/ollipal/sshkeyboard/blob/main/README.md Shows two methods to stop the keyboard listener: by specifying a key to stop listening with the `until` parameter, or by programmatically calling `stop_listening()` from within a callback function. Setting `until=None` disables automatic stopping. ```python from sshkeyboard import listen_keyboard def press(key): print(f"'{key}' pressed") # Stop listening when 'space' is pressed # listen_keyboard( # on_press=press, # until="space", # ) from sshkeyboard import listen_keyboard, stop_listening def press_and_stop(key): print(f"'{key}' pressed") if key == "z": stop_listening() # Stop listening when 'z' is pressed by calling stop_listening() # listen_keyboard(on_press=press_and_stop) ``` -------------------------------- ### Custom Stop Key Source: https://context7.com/ollipal/sshkeyboard/llms.txt Customize the key that terminates the keyboard listening session. ```APIDOC ## listen_keyboard with custom stop key ### Description Demonstrates how to set a custom key to stop the keyboard listener using the `until` parameter. ### Method `listen_keyboard(on_press=press, until="space")` or `listen_keyboard(on_press=press, until=None)` ### Parameters - **until** (str or None) - The key to stop listening. Set to a specific key name (e.g., "space") or `None` to disable the stop key. ### Request Example ```python from sshkeyboard import listen_keyboard def press(key): print(f"'{key}' pressed") # Listen until 'space' is pressed listen_keyboard(on_press=press, until="space") # Listen indefinitely listen_keyboard(on_press=press, until=None) ``` ### Response #### Success Response (None) No direct response, the listener behavior is modified. #### Response Example None ``` -------------------------------- ### Adjust Timing Parameters for Key Press Detection Source: https://context7.com/ollipal/sshkeyboard/llms.txt Allows adjustment of timing parameters to improve key press detection accuracy across different terminals. Use `delay_second_char` to set the timeout between the first and second characters of a key press, and `delay_other_chars` for subsequent characters. ```python from sshkeyboard import listen_keyboard def press(key): print(f"'{key}' pressed") # Adjust timing parameters listen_keyboard( on_press=press, delay_second_char=0.75, # Timeout between first and second char (default: 0.75) delay_other_chars=0.05, # Timeout between subsequent chars (default: 0.05) ) ``` -------------------------------- ### Control Case Sensitivity of Key Input Source: https://context7.com/ollipal/sshkeyboard/llms.txt Provides control over whether keyboard input is converted to lowercase. Set `lower=True` (default) to convert all keys to lowercase, or `lower=False` to preserve the original case of pressed keys, including shifted characters. ```python from sshkeyboard import listen_keyboard def press(key): print(f"'{key}' pressed") # Default: lower=True (converts 'A' to 'a') listen_keyboard(on_press=press, lower=True) # Preserve original case listen_keyboard(on_press=press, lower=False) # Now pressing Shift+A will output: # 'A' pressed ``` -------------------------------- ### Adjust Sleep Duration for Input Reads Source: https://context7.com/ollipal/sshkeyboard/llms.txt Enables adjustment of the sleep duration within `asyncio.sleep()` between reading keyboard input. Shorter sleep times (`sleep=0.001`) increase responsiveness at the cost of higher CPU usage, while longer times (`sleep=0.05`) reduce CPU usage but decrease responsiveness. ```python from sshkeyboard import listen_keyboard def press(key): print(f"'{key}' pressed") # Adjust asyncio.sleep() amount between input reads listen_keyboard( on_press=press, sleep=0.01, # Default: 0.01 seconds ) # Increase for lower CPU usage (less responsive) listen_keyboard(on_press=press, sleep=0.05) # Decrease for higher responsiveness (more CPU usage) listen_keyboard(on_press=press, sleep=0.001) ``` -------------------------------- ### Programmatic Stop Listening Source: https://context7.com/ollipal/sshkeyboard/llms.txt Stop the keyboard listener at any time, either from within a callback function or from external code, using the `stop_listening()` function. ```APIDOC ## stop_listening ### Description Programmatically stops the `sshkeyboard` listener. Can be called from within callback functions or other parts of your code. ### Method `stop_listening()` ### Parameters None ### Request Example ```python from sshkeyboard import listen_keyboard, stop_listening def press(key): print(f"'{key}' pressed") if key == "z": print("Stopping listener...") stop_listening() listen_keyboard(on_press=press) ``` ### Response #### Success Response (None) This function halts the `listen_keyboard` process. #### Response Example None ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.