### Install development dependencies Source: https://github.com/magmax/python-readchar/blob/master/CONTRIBUTING.md Install all necessary development dependencies, including the library in editable mode. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install python-readchar Source: https://github.com/magmax/python-readchar/blob/master/README.md Install the library using pip. This is the standard method for adding packages to your Python environment. ```bash pip install readchar ``` -------------------------------- ### Menu Navigation Example Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/quick-reference.md Demonstrates menu navigation using UP and DOWN arrows to change selection and ENTER to confirm. Handles wrapping around options. ```python from readchar import readkey, key current = 0 options = ["Option 1", "Option 2", "Option 3"] while True: print(f"> {options[current]}) k = readkey() if k == key.UP: current = (current - 1) % len(options) elif k == key.DOWN: current = (current + 1) % len(options) elif k == key.ENTER: return options[current] ``` -------------------------------- ### Basic Key Reading Example Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/library-overview.md Demonstrates basic usage of `readkey()` to capture a keystroke and compare it against predefined key constants like `key.UP` and `key.DOWN`. ```python from readchar import readkey, key k = readkey() if k == key.UP: move_up() elif k == key.DOWN: move_down() ``` -------------------------------- ### Interrupt Handling Example Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/library-overview.md Shows how to handle `KeyboardInterrupt` exceptions when reading keys, allowing for graceful interruption of loops or operations. ```python from readchar import readkey try: while True: k = readkey() except KeyboardInterrupt: print("User interrupted") ``` -------------------------------- ### Cross-Platform Key Comparison Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/README.md This example demonstrates how to compare key presses in a cross-platform manner using the `key` constants. Avoid hardcoding specific key values. ```python from readchar import readkey, key k = readkey() if k == key.UP: # Works on all platforms pass ``` -------------------------------- ### Version Information Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/exports.md Retrieves the installed version of the readchar package. This is typically accessed via __version__. ```python from readchar import __version__ __version__ # "4.2.3-dev0" ``` -------------------------------- ### __version__ Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/exports.md Provides the version information for the readchar package. This is a public attribute accessible for checking the installed version. ```APIDOC ## __version__ ### Description Version information for the readchar package. ### Type `str` ### Usage Example ```python from readchar import __version__ print(f"Using readchar version: {__version__}") ``` ``` -------------------------------- ### Common Key Constants Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/quick-reference.md Examples of common key constants available in the readchar library, such as CTRL_C, ENTER, SPACE, TAB, and ESC. ```python key.CTRL_C # Interrupt (0x03) key.ENTER # Return key key.SPACE # Space key.TAB # Tab key.ESC # Escape ``` -------------------------------- ### Basic Exception Handling for readkey() Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/errors.md A fundamental example of handling both KeyboardInterrupt and OSError exceptions that might be raised by the readkey() function in a typical application. ```python from readchar import readkey import sys try: k = readkey() except KeyboardInterrupt: print("User interrupt") sys.exit(0) except OSError as e: print(f"Terminal error: {e}") sys.exit(1) ``` -------------------------------- ### Example Usage of readchar() Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/windows-implementation.md Demonstrates reading characters from the console using readchar() until an EOF or error occurs, printing each character received. ```python import readchar # Read characters until EOF or error while True: try: ch = readchar.readchar() print(f"Got: {repr(ch)}") if ch == '\n': break except OSError: print("Console input error") break ``` -------------------------------- ### Basic Key Comparison Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/key-module.md Compare keystrokes against key constants to detect specific key presses like UP, DOWN, or ENTER. This example breaks the loop when ENTER is pressed. ```python from readchar import readkey, key while True: k = readkey() if k == key.UP: print("Up arrow pressed") elif k == key.DOWN: print("Down arrow pressed") elif k == key.ENTER: print("Enter pressed") break ``` -------------------------------- ### Special Combinations (POSIX) Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/quick-reference.md Examples of special key combinations available on POSIX systems, such as SHIFT_TAB and CTRL_ALT_SUPR, and patterns like ESC + letter. ```python key.SHIFT_TAB key.CTRL_ALT_SUPR key.ALT_A # Pattern: ESC + letter key.CTRL_ALT_A # Pattern: ESC + control code ``` -------------------------------- ### Persist Configuration with Context Manager Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/quick-reference.md Uses a context manager to temporarily change interrupt keys and restore them afterward. This example sets interrupt to CTRL+Q within the 'with' block. ```python from readchar import config, key from contextlib import contextmanager @contextmanager def custom_interrupts(*keys): old = config.INTERRUPT_KEYS config.INTERRUPT_KEYS = list(keys) try: yield finally: config.INTERRUPT_KEYS = old # Usage with custom_interrupts(key.CTRL_Q): k = readkey() # Uses CTRL+Q for interrupt ``` -------------------------------- ### Print Interrupt Keys Configuration Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/README.md This snippet shows how to print the configured interrupt keys. It is useful for understanding the library's interrupt handling setup. ```python from readchar import config print(config.INTERRUPT_KEYS) ``` -------------------------------- ### Read a single character Source: https://github.com/magmax/python-readchar/blob/master/README.md Import the library and use the readkey() function to capture a single keystroke. This is the most basic way to get user input. ```python import readchar key = readchar.readkey() ``` -------------------------------- ### Custom Configuration for Interrupt Keys Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/library-overview.md Illustrates how to customize which keys trigger a `KeyboardInterrupt` by modifying the `config.INTERRUPT_KEYS` list. This example sets only CTRL+Q as the interrupt key. ```python from readchar import config, key, readkey # Only CTRL+Q raises interrupt config.INTERRUPT_KEYS = [key.CTRL_Q] k = readkey() ``` -------------------------------- ### Read and Identify Key Press Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/posix-implementation.md Example of reading a single key press using readkey() and then identifying it using predefined key constants. This covers basic arrow keys, function keys, and general character input. ```python from readchar import readkey, key # Read and identify key k = readkey() if k == key.UP: print("Up arrow") elif k == key.DOWN: print("Down arrow") elif k == key.F1: print("F1 key") elif k == key.ENTER: print("Enter") else: print(f"Got: {repr(k)}") ``` -------------------------------- ### Read Complete Keystroke Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/quick-reference.md Use readkey() to read a complete keystroke, including multi-character escape sequences. This example checks for UP arrow and ENTER keys. ```python k = readkey() if k == key.UP: print("Up arrow") elif k == key.ENTER: print("Enter") ``` -------------------------------- ### Handling OSError in readchar() Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/errors.md Provides a basic example of catching OSError when using readchar(), which can occur due to terminal access issues or I/O errors. ```python from readchar import readchar import sys try: ch = readchar() except OSError as e: print(f"Cannot read from terminal: {e}", file=sys.stderr) sys.exit(1) ``` -------------------------------- ### Function Key Handling Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/key-module.md Detect presses of function keys like F1, F2, or F10 using their respective constants. This example breaks the loop when F10 is pressed. ```python from readchar import readkey, key while True: k = readkey() if k == key.F1: show_help() elif k == key.F2: show_search() elif k == key.F10: break ``` -------------------------------- ### Accessing Configuration - Python Readchar Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/config.md Access configuration attributes directly from the static `config` class without instantiation. This example shows how to check the current interrupt keys and determine if CTRL+C is configured. ```python from readchar import config, key # Check current interrupt keys print(config.INTERRUPT_KEYS) # ["\x03"] # Check if CTRL+C is configured as interrupt if key.CTRL_C in config.INTERRUPT_KEYS: print("CTRL+C will raise KeyboardInterrupt") ``` -------------------------------- ### Customize INTERRUPT_KEYS Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/configuration.md Modify the `config.INTERRUPT_KEYS` list to change which keys raise KeyboardInterrupt. This example demonstrates setting custom interrupt keys and disabling interrupts entirely. ```python from readchar import config, key, readkey # Default behavior - only CTRL+C raises interrupt try: while True: k = readkey() except KeyboardInterrupt: print("Interrupted") # Customize interrupt keys config.INTERRUPT_KEYS = [key.CTRL_C, key.CTRL_D] try: while True: k = readkey() except KeyboardInterrupt: print("Interrupted by CTRL+C or CTRL+D") # Disable interrupts config.INTERRUPT_KEYS = [] # Now CTRL+C is returned as a normal key k = readkey() if k == "\x03": # or key.CTRL_C print("CTRL+C pressed (not interrupted)") # Restore default config.INTERRUPT_KEYS = [key.CTRL_C] ``` -------------------------------- ### Test build process with setup.py Source: https://github.com/magmax/python-readchar/blob/master/CONTRIBUTING.md Test the build process by creating source and wheel distributions. ```bash python setup.py sdist bdist_wheel ``` -------------------------------- ### Run all tests with make Source: https://github.com/magmax/python-readchar/blob/master/CONTRIBUTING.md Execute all project tests, including linting and building, using the 'make' command. ```bash make ``` -------------------------------- ### Create a virtual environment Source: https://github.com/magmax/python-readchar/blob/master/CONTRIBUTING.md Create a Python virtual environment to isolate project dependencies. ```bash python -m venv .venv ``` -------------------------------- ### Backwards Compatibility Import Options Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/key-module.md Demonstrates the two supported import methods for the `key` module to ensure backwards compatibility. ```python # Both of these work from readchar import key import readchar.key ``` -------------------------------- ### Activate virtual environment (Linux) Source: https://github.com/magmax/python-readchar/blob/master/CONTRIBUTING.md Activate the created virtual environment on Linux systems. ```bash source .venv/bin/activate ``` -------------------------------- ### Run pre-commit for linting and styling Source: https://github.com/magmax/python-readchar/blob/master/CONTRIBUTING.md Manually run pre-commit hooks for linting and styling checks. ```bash pre-commit run -a ``` -------------------------------- ### SyntaxError: Config Instantiation Error Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/errors.md This error arises when attempting to create an instance of the configuration class, which is not designed for direct instantiation. ```text SyntaxError: you can't create instances of this class ``` -------------------------------- ### Import Configuration Class Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/configuration.md Import the configuration class from the readchar library. ```python from readchar import config ``` -------------------------------- ### Activate virtual environment (Windows) Source: https://github.com/magmax/python-readchar/blob/master/CONTRIBUTING.md Activate the created virtual environment on Windows systems. ```bash .venv\Scripts\activate ``` -------------------------------- ### Basic Import Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/quick-reference.md Import core functions and constants from the readchar library. ```python from readchar import readchar, readkey, key, config ``` -------------------------------- ### Clone the repository Source: https://github.com/magmax/python-readchar/blob/master/CONTRIBUTING.md Clone the project repository to your local machine and navigate into the project directory. ```bash git clone https://github.com/magmax/python-readchar.git cd python-readchar ``` -------------------------------- ### Cross-Platform Key Handling with readchar Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/key-module.md Illustrates how `readchar` ensures consistent behavior for key constants like `key.DOWN` across different operating systems, abstracting platform-specific differences. ```python from readchar import key, readkey # This works the same on all platforms k = readkey() if k == key.DOWN: # This branch executes regardless of platform move_cursor_down() ``` -------------------------------- ### Basic Key Reading with readkey() Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/readkey.md Demonstrates reading a single key press and comparing it to a character or a special key constant. Use this for simple input handling. ```python from readchar import readkey, key # Basic key reading k = readkey() if k == "a": print("You pressed 'a'") elif k == key.DOWN: print("You pressed DOWN arrow") elif k == key.ENTER: print("You pressed Enter") ``` -------------------------------- ### Module Initialization Configuration Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/configuration.md Apply global configuration settings for `INTERRUPT_KEYS` by importing a module that sets them at import time. This affects the entire application. ```python # config_setup.py from readchar import config, key # Global configuration config.INTERRUPT_KEYS = [key.CTRL_C, key.CTRL_Q] ``` ```python # main.py import config_setup # Apply configuration from readchar import readkey while True: k = readkey() # Uses custom INTERRUPT_KEYS ``` -------------------------------- ### Configure Interrupt Keys Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/configuration.md Set `config.INTERRUPT_KEYS` to a list of key constants to define which key presses should trigger an interrupt. This example shows setting 'CTRL_C' as an interrupt key. ```python config.INTERRUPT_KEYS = [key.CTRL_C] # Correct: Use key constant ``` -------------------------------- ### Correct Usage of readchar Configuration Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/errors.md Demonstrates the correct way to use the readchar.config object by accessing its attributes directly, rather than attempting to instantiate it. ```python from readchar import config # Access attributes directly - do not instantiate config.INTERRUPT_KEYS = [...] ``` -------------------------------- ### Handling Control Keys with readchar Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/key-module.md Demonstrates how to detect and react to specific control key presses like CTRL+S, CTRL+Z, and CTRL+C using the `readkey` function and `key` constants. ```python from readchar import readkey, key while True: k = readkey() if k == key.CTRL_S: save_file() elif k == key.CTRL_Z: undo() elif k == key.CTRL_C: # Normally raises KeyboardInterrupt, but can be configured break ``` -------------------------------- ### Modifying Interrupt Keys - Python Readchar Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/config.md Modify the `INTERRUPT_KEYS` list to include additional keys that should trigger a `KeyboardInterrupt`. This example adds CTRL+D as an interrupt key alongside CTRL+C. ```python from readchar import config, key, readkey # Make both CTRL+C and CTRL+D interrupt config.INTERRUPT_KEYS = [key.CTRL_C, key.CTRL_D] try: while True: k = readkey() print(f"Key: {repr(k)}") except KeyboardInterrupt: print("Interrupt key pressed (CTRL+C or CTRL+D)") ``` -------------------------------- ### Custom Interrupt Keys - Python Readchar Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/config.md Replace the default interrupt keys with custom ones by assigning a new list to `config.INTERRUPT_KEYS`. This example configures CTRL+Q as the sole interrupt key. ```python from readchar import config, key, readkey # Use CTRL+Q to exit instead config.INTERRUPT_KEYS = [key.CTRL_Q] try: while True: k = readkey() print(f"Key: {repr(k)}") except KeyboardInterrupt: print("User pressed CTRL+Q") ``` -------------------------------- ### Control Key Constants Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/quick-reference.md Illustrates the pattern for control keys (CTRL+A through CTRL+Z) using key constants. ```python key.CTRL_A through key.CTRL_Z # CTRL+A through CTRL+Z ``` -------------------------------- ### Inspecting Platform-Specific Key Values Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/key-module.md Shows how to use `repr()` with `key` constants to inspect their actual platform-specific escape sequence values, including the consistent value for CTRL+C. ```python from readchar import key print(repr(key.UP)) # Shows platform-specific escape sequence print(repr(key.DOWN)) # Shows platform-specific escape sequence print(repr(key.CTRL_C)) # Always "\x03" ``` -------------------------------- ### Correct Key String Matching for INTERRUPT_KEYS Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/configuration.md Demonstrates the correct way to assign key constants or their raw string values to `config.INTERRUPT_KEYS` for accurate matching. ```python from readchar import config, key # Correct config.INTERRUPT_KEYS = [key.CTRL_C] # "\x03" # Also correct config.INTERRUPT_KEYS = ["\x03"] ``` -------------------------------- ### Thread-Safe Key Reading with Queue Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/quick-reference.md Demonstrates a thread-safe approach to reading keys by using a separate thread to read keys and put them into a queue, which the main thread then retrieves. ```python import threading from readchar import readkey import queue q = queue.Queue() def reader(): while True: try: k = readkey() q.put(k) except Exception as e: q.put(e) thread = threading.Thread(target=reader, daemon=True) thread.start() # Read from queue instead k = q.get() ``` -------------------------------- ### SyntaxError on Instantiating config Class Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/errors.md Illustrates the SyntaxError that occurs when attempting to create an instance of the readchar.config class, as it's intended for static access only. ```python from readchar import config config() # SyntaxError: you can't create instances of this class ``` -------------------------------- ### Importing the Key Module Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/exports.md This code shows the two supported import patterns for the `readchar.key` module, ensuring backwards compatibility. The `readchar/key.py` file handles re-exporting symbols from the platform-specific key module. ```python from readchar import key import readchar.key ``` -------------------------------- ### Platform-Specific Module Loading Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/exports.md This code demonstrates how the library dynamically imports the correct platform-specific module for reading characters and keys based on the operating system. It ensures that the appropriate implementation is used at import time. ```python import platform if platform.startswith(("linux", "darwin", "freebsd", "openbsd", "android")): from . import _posix_key as key from ._posix_read import readchar, readkey elif platform in ("win32", "cygwin"): from . import _win_key as key from ._win_read import readchar, readkey else: raise NotImplementedError(f"The platform {platform} is not supported yet") ``` -------------------------------- ### Menu Navigation Loop with readkey() Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/readkey.md Illustrates using readkey() in a loop for interactive menu navigation. This snippet shows how to process directional keys and exit commands. ```python from readchar import readkey, key # Menu loop menu_active = True while menu_active: k = readkey() if k == "q": menu_active = False elif k == key.UP: print("Move up") elif k == key.DOWN: print("Move down") elif k == key.LEFT: print("Move left") elif k == key.RIGHT: print("Move right") ``` -------------------------------- ### Configuration Class Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/exports.md Provides static configuration options for the readchar library. Use this to customize interrupt keys. ```python from readchar import config class config: INTERRUPT_KEYS: List[str] ``` -------------------------------- ### Import the key module Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/key-module.md Import the key module directly or as a submodule. This allows access to platform-independent key constants. ```python from readchar import key ``` ```python import readchar.key as key ``` -------------------------------- ### Read Multiple Characters with readchar Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/posix-implementation.md Demonstrates reading a sequence of characters using the readchar function and printing each character as it's read. ```python import readchar # Read characters until all 10 are collected chars = [] for _ in range(10): ch = readchar.readchar() chars.append(ch) print(f"Read: {repr(ch)}") result = ''.join(chars) print(f"Got: {result}") ``` -------------------------------- ### readchar.key module Source: https://github.com/magmax/python-readchar/blob/master/README.md Provides a submodule containing constants for available keys. These constants are OS-dependent and allow for portable comparison of key presses with the output of readkey(). ```APIDOC ## readchar.key module ### Description This submodule contains a list of available keys to compare against. The constants are defined depending on your operating system, so it should be fully portable. If a key is listed here for your platform, `readkey()` can read it, and you can compare against it. ### Usage ```python from readchar import key if k == key.DOWN: # do stuff ``` ``` -------------------------------- ### Key Aliases Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/exports.md Provides aliases for common keys like ENTER and DELETE for cross-platform consistency. ```python key.ENTER # Alias for appropriate return key key.DELETE # Alias for SUPR ``` -------------------------------- ### Save and Restore Configuration Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/configuration.md Temporarily change `config.INTERRUPT_KEYS` and then restore it to its original value using a try-finally block. This is useful for localized configuration changes. ```python from readchar import config, key, readkey # Save original original_interrupt_keys = config.INTERRUPT_KEYS[:] try: # Use custom configuration config.INTERRUPT_KEYS = [] # Read without interrupts k = readkey() finally: # Restore config.INTERRUPT_KEYS = original_interrupt_keys ``` -------------------------------- ### Import Dependencies for Windows Implementation Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/windows-implementation.md Imports the necessary msvcrt module for Windows console I/O and the internal config module for interrupt key settings. ```python import msvcrt from ._config import config ``` -------------------------------- ### Control Keys (CTRL+X) Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/types.md Control key constants are available on all platforms. ```python CTRL_A: str = "\x01" CTRL_B: str = "\x02" CTRL_C: str = "\x03" CTRL_D: str = "\x04" CTRL_E: str = "\x05" CTRL_F: str = "\x06" CTRL_G: str = "\x07" CTRL_H: str = "\x08" CTRL_I: str = "\t" CTRL_J: str = "\x0a" CTRL_K: str = "\x0b" CTRL_L: str = "\x0c" CTRL_M: str = "\x0d" CTRL_N: str = "\x0e" CTRL_O: str = "\x0f" CTRL_P: str = "\x10" CTRL_Q: str = "\x11" CTRL_R: str = "\x12" CTRL_S: str = "\x13" CTRL_T: str = "\x14" CTRL_U: str = "\x15" CTRL_V: str = "\x16" CTRL_W: str = "\x17" CTRL_X: str = "\x18" CTRL_Y: str = "\x19" CTRL_Z: str = "\x1a" ``` -------------------------------- ### Access Key Constants Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/library-overview.md Import the `key` module from the `readchar` package to access platform-appropriate key constants for type-safe comparisons. ```python from readchar import key ``` -------------------------------- ### Handling RuntimeError in readkey() Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/errors.md Shows how to catch a RuntimeError, which might occur on Windows due to character encoding issues with surrogate pairs during readkey() execution. ```python from readchar import readkey try: k = readkey() except RuntimeError as e: print(f"Character encoding error: {e}") ``` -------------------------------- ### Global Configuration Class Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/library-overview.md The `config` class provides static configuration options for the library, such as defining interrupt keys. ```python class config Static configuration class with INTERRUPT_KEYS attribute. ``` -------------------------------- ### Menu Navigation with Key Constants Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/key-module.md Use UP and DOWN arrow key constants to navigate through menu options. The ENTER key constant is used to select an option and return it. ```python from readchar import readkey, key def menu(): options = ["Option 1", "Option 2", "Option 3"] current = 0 while True: print(f"Selected: {options[current]}") k = readkey() if k == key.UP: current = (current - 1) % len(options) elif k == key.DOWN: current = (current + 1) % len(options) elif k == key.ENTER: return options[current] ``` -------------------------------- ### POSIX Extended Navigation Keys Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/types.md Extended navigation key constants for POSIX systems. ```python INSERT: str = "\x1b\x5b\x32\x7e" SUPR: str = "\x1b\x5b\x33\x7e" HOME: str = "\x1b\x5b\x48" END: str = "\x1b\x5b\x46" PAGE_UP: str = "\x1b\x5b\x35\x7e" PAGE_DOWN: str = "\x1b\x5b\x36\x7e" ``` -------------------------------- ### Navigation Key Constants Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/quick-reference.md Lists common navigation key constants available on different platforms, including arrow keys, HOME, END, INSERT, SUPR, and PAGE UP/DOWN. ```python key.UP, key.DOWN, key.LEFT, key.RIGHT key.HOME, key.END key.INSERT, key.SUPR (or key.DELETE) key.PAGE_UP, key.PAGE_DOWN ``` -------------------------------- ### Module Exports Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/library-overview.md The `readchar` package exports the `readchar`, `readkey`, `key`, and `config` symbols. ```python __all__ = ["readchar", "readkey", "key", "config"] ``` -------------------------------- ### Run pytest for source-code testing Source: https://github.com/magmax/python-readchar/blob/master/CONTRIBUTING.md Manually run the source-code tests using pytest. ```bash pytest ``` -------------------------------- ### Type Checking and Usage of Key Constants Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/types.md Demonstrates that all key constants are of type string and can be directly compared or used in collections. This snippet is useful for understanding how to interact with key presses in your application. ```python from readchar import key # All key constants are str type isinstance(key.ENTER, str) # True isinstance(key.UP, str) # True isinstance(key.CTRL_C, str) # True # They can be compared directly if readkey() == key.DOWN: print("Down arrow pressed") # Or used in collections arrow_keys = [key.UP, key.DOWN, key.LEFT, key.RIGHT] ``` -------------------------------- ### Handling KeyboardInterrupt with readkey() Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/readkey.md Shows how to use a try-except block to catch KeyboardInterrupt when readkey() is used. This is useful for gracefully handling user interruptions like CTRL+C. ```python from readchar import readkey, key # Catch interrupts try: while True: k = readkey() print(f"Pressed: {repr(k)}") except KeyboardInterrupt: print("User pressed CTRL+C") ``` -------------------------------- ### Common Key Constants Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/exports.md Lists common key constants available on all platforms, including basic characters and control keys. ```python from readchar import key # Basic characters key.LF # Line feed key.CR # Carriage return key.SPACE # Space key.ESC # Escape key.TAB # Tab ``` ```python # CTRL combinations key.CTRL_A, key.CTRL_B, key.CTRL_C, ...key.CTRL_Z ``` -------------------------------- ### Context Manager for Safe Terminal Access with readkey() Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/errors.md Implements a context manager to safely use readkey(), ensuring that KeyboardInterrupt and OSError exceptions are caught and re-raised, providing a cleaner way to handle terminal input. ```python from contextlib import contextmanager from readchar import readkey @contextmanager def safe_readkey(): try: yield readkey() except KeyboardInterrupt: print("Interrupted") raise except OSError: print("Cannot read from terminal") raise # Usage try: with safe_readkey() as k: print(f"Got key: {repr(k)}") except (KeyboardInterrupt, OSError): pass ``` -------------------------------- ### Safely Handling Unknown Keys with readchar Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/key-module.md Provides a function to read keys using `readkey`, handle known keys (UP, DOWN, 'a', 'b', 'c'), and represent unknown keys by their hexadecimal representation. ```python from readchar import readkey, key def safe_readkey(): k = readkey() # Handle known keys if k == key.UP: return "up" elif k == key.DOWN: return "down" elif k in ("a", "b", "c"): return k else: # Unknown key, show its hex representation return f"unknown: {repr(k)}" while True: result = safe_readkey() print(f"Got: {result}") ``` -------------------------------- ### Handle KeyboardInterrupt Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/quick-reference.md Demonstrates catching KeyboardInterrupt exceptions, typically raised by CTRL+C, and printing an 'Interrupted' message. ```python try: while True: k = readkey() except KeyboardInterrupt: print("Interrupted") ``` -------------------------------- ### Import Dependencies for POSIX Readchar Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/posix-implementation.md Imports necessary modules for stdin access, platform detection, and terminal I/O control in the POSIX implementation. ```python import sys import termios from ._config import config ``` -------------------------------- ### Module Import Pattern Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/exports.md Imports the entire readchar package as a module. Access symbols as attributes (e.g., readchar.readkey()). ```python import readchar # Access as attributes readchar.readchar() readchar.readkey() readchar.key.UP readchar.config.INTERRUPT_KEYS ``` -------------------------------- ### Individual Imports Pattern Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/exports.md Imports specific symbols from the readchar package. Recommended for clarity and to avoid namespace pollution. ```python from readchar import readkey, key from readchar import config ``` -------------------------------- ### React to different key presses Source: https://github.com/magmax/python-readchar/blob/master/README.md Use a loop to continuously read keystrokes and conditionally execute code based on the key pressed. This allows for interactive command-line applications. ```python from readchar import readkey, key while True: k = readkey() if k == "a": # do stuff if k == key.DOWN: # do stuff if k == key.ENTER: break ``` -------------------------------- ### Per-Function Configuration with Context Manager Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/configuration.md Use a custom context manager to temporarily change `config.INTERRUPT_KEYS` within a specific block of code. The configuration is automatically restored upon exiting the block. ```python from readchar import config, key, readkey from contextlib import contextmanager @contextmanager def custom_interrupts(*interrupt_keys): old = config.INTERRUPT_KEYS config.INTERRUPT_KEYS = list(interrupt_keys) try: yield finally: config.INTERRUPT_KEYS = old # Usage with custom_interrupts(key.CTRL_C, key.CTRL_D): k = readkey() # Uses custom interrupts ``` -------------------------------- ### key Module Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/exports.md A module providing platform-appropriate key constants for use with the readchar library. This module is exported as part of the public API. ```APIDOC ## key Module ### Description Platform-appropriate key constants module. ### Module Type Returns all constants from platform-specific implementation. ### Exported Constants - **Common Keys:** `key.LF`, `key.CR`, `key.SPACE`, `key.ESC`, `key.TAB`, etc. - **Control Keys:** `key.CTRL_A` through `key.CTRL_Z`. - **Platform-Specific Keys:** Includes arrow keys, function keys, etc., varying by OS. - **Aliases:** `key.ENTER` (alias for return key), `key.DELETE` (alias for SUPR). ### Usage Example ```python from readchar import key if char == key.CTRL_C: print("Ctrl+C pressed") ``` ### Documentation See [api-reference/key-module.md](key-module.md) and [types.md](../types.md) for a complete listing. ``` -------------------------------- ### Handle Function Keys Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/README.md Detect and respond to function key presses like F1, F2, and F10 for specific actions within an application. ```python from readchar import readkey, key while True: k = readkey() if k == key.F1: show_help() elif k == key.F2: edit() elif k == key.F10: save_and_exit() ``` -------------------------------- ### Submodule Import Pattern Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/exports.md Imports the 'key' submodule specifically, either as 'key' or with an alias. This is a common way to access key constants. ```python import readchar.key as key # or from readchar import key ``` -------------------------------- ### POSIX readkey State Machine Logic Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/posix-implementation.md Illustrates the state transitions for parsing ANSI escape sequences to identify special keys like arrows and function keys. ```python State 0: Read c1 ├─ c1 in config.INTERRUPT_KEYS? → raise KeyboardInterrupt ├─ c1 == 0x1B (ESC)? → go to State 1 └─ else → return c1 State 1: Read c2 (after ESC) ├─ c2 in [0x4F, 0x5B]? → go to State 2 └─ else → return c1 + c2 State 2: Read c3 ├─ c3 in [0x31, 0x32, 0x33, 0x35, 0x36]? → go to State 3 └─ else → return c1 + c2 + c3 State 3: Read c4 ├─ c4 in [0x30, 0x31, 0x33, 0x34, 0x35, 0x37, 0x38, 0x39]? → go to State 4 └─ else → return c1 + c2 + c3 + c4 State 4: Read c5 └─ return c1 + c2 + c3 + c4 + c5 ``` -------------------------------- ### Compare Special Key Input Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/quick-reference.md Compares the readkey() output to predefined key constants for special keys like ENTER, UP arrow, and F1. ```python if k == key.ENTER: print("Enter pressed") if k == key.UP: print("Up arrow") if k == key.F1: print("F1 key") ``` -------------------------------- ### readkey() Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/windows-implementation.md Reads a complete keystroke from the Windows console, handling scan code sequences for special keys and UTF-16 surrogates for wide characters. It assembles multi-character sequences into a single logical keypress. ```APIDOC ## readkey() ### Description Reads a complete keystroke from the Windows console, correctly interpreting special keys and wide characters. ### Signature ```python def readkey() -> str ``` ### Functionality This function reads characters sequentially, checks for interrupt keys, parses scan code prefixes for special keys (like arrow keys and function keys), and handles UTF-16 surrogate pairs to correctly represent wide Unicode characters. It returns a string representing the complete logical keystroke. ### Detailed Algorithm 1. Reads the first character using `readchar()`. 2. Checks if the character is an interrupt key (e.g., Ctrl+C). 3. If the character is a scan code prefix (`\x00` or `\xe0`), it reads the subsequent scan code byte and normalizes the prefix to `\x00`. 4. If the character is a UTF-16 surrogate, it reads the second surrogate byte and combines them into a single Unicode character. ### Return Value `str` - A string representing the key pressed. This can be a regular character, a special key sequence (e.g., `\x00\x48` for UP arrow), or a wide Unicode character. ``` -------------------------------- ### Windows Navigation Keys Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/types.md Navigation key constants specific to Windows systems. ```python BACKSPACE: str = "\x08" UP: str = "\x00\x48" DOWN: str = "\x00\x50" LEFT: str = "\x00\x4b" RIGHT: str = "\x00\x4d" ``` -------------------------------- ### readchar.readkey() Source: https://github.com/magmax/python-readchar/blob/master/README.md Reads the next keystroke from standard input and returns it as a string. This method handles single characters, special keys (like ENTER, BACKSPACE), arrow keys, navigation keys, function keys, and combinations with CTRL, ALT, and CTRL+ALT. ```APIDOC ## readchar.readkey() ### Description Reads the next keystroke from `stdin`, returning it as a string. Waits until a keystroke is available. This method handles various types of keys including normal characters, special keys, arrow keys, navigation keys, function keys, and combinations with modifier keys (CTRL, ALT). ### Method `readkey()` ### Parameters None ### Response - Returns: `str` - The next keystroke as a string. This can be a single character or a special key sequence. ``` -------------------------------- ### POSIX Navigation Keys Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/types.md Navigation key constants specific to POSIX systems. ```python BACKSPACE: str = "\x7f" UP: str = "\x1b\x5b\x41" DOWN: str = "\x1b\x5b\x42" LEFT: str = "\x1b\x5b\x44" RIGHT: str = "\x1b\x5b\x43" ``` -------------------------------- ### Resilient Loop for Multiple Key Reads Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/errors.md Shows a robust loop structure for applications that continuously read multiple keys, handling KeyboardInterrupt for graceful exit and OSError for read errors. ```python from readchar import readkey import sys while True: try: k = readkey() process_key(k) except KeyboardInterrupt: print("\nQuitting...") break except OSError as e: print(f"Error reading key: {e}") # Decide whether to retry or exit break ``` -------------------------------- ### Terminal-Based User Interfaces Menu Navigation Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/README.md Use readkey() to navigate menus in a terminal application. Handles UP, DOWN, and ENTER keys to control a selected item. ```python from readchar import readkey, key current_item = 0 while True: k = readkey() if k == key.UP: current_item = max(0, current_item - 1) elif k == key.DOWN: current_item += 1 elif k == key.ENTER: select(current_item) break ``` -------------------------------- ### POSIX Aliases Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/types.md Aliases for common keys on POSIX systems. ```python ENTER: str = LF DELETE: str = SUPR ``` -------------------------------- ### Common Key Constants Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/types.md These common constants are exported across all platforms. ```python # Line Feed (newline) LF: str = "\x0a" # Carriage Return CR: str = "\x0d" # Space character SPACE: str = "\x20" # Escape character ESC: str = "\x1b" # Tab character TAB: str = "\x09" ``` -------------------------------- ### readkey() Source: https://github.com/magmax/python-readchar/blob/master/_autodocs/api-reference/readkey.md Reads the next keystroke from the standard input stream, blocking until one is available. It intelligently handles multi-character escape sequences for special keys like arrow keys and function keys. ```APIDOC ## readkey() ### Description Reads the next keystroke from stdin and returns it as a string. Handles multi-character escape sequences for special keys. ### Signature ```python def readkey() -> str ``` ### Parameters None ### Return Type `str` — A keystroke, which can be: - A single character (normal keys, special characters, CTRL combinations) - A multi-character string (arrow keys, function keys, ALT/CTRL+ALT combinations) ### Description This function reads the next keystroke from the standard input stream, blocking until one is available. Unlike `readchar()`, it intelligently handles multi-character escape sequences that represent single logical keystrokes (arrow keys, function keys, etc.). The function reads the first character and checks if it is an escape character (`\x1B`). If so, it reads additional characters to form the complete key sequence. The exact sequences depend on the platform: - **POSIX systems:** Uses ANSI escape codes - **Windows:** Uses Windows scan codes (which start with `\x00` or `\xe0`) The function respects the `config.INTERRUPT_KEYS` setting. By default, pressing CTRL+C will raise `KeyboardInterrupt` rather than returning the key. ### Raises | Exception | Condition | |-----------|-----------| | `KeyboardInterrupt` | When an interrupt key (default: CTRL+C) is pressed | | `OSError` | On POSIX systems, if termios operations fail | ### Exceptions `KeyboardInterrupt` is raised when a key in `readchar.config.INTERRUPT_KEYS` is detected. The default list contains only `key.CTRL_C`. To handle CTRL+C yourself, use `readchar()` instead. ### Example ```python from readchar import readkey, key # Basic key reading k = readkey() if k == "a": print("You pressed 'a'") elif k == key.DOWN: print("You pressed DOWN arrow") elif k == key.ENTER: print("You pressed Enter") # Menu loop menu_active = True while menu_active: k = readkey() if k == "q": menu_active = False elif k == key.UP: print("Move up") elif k == key.DOWN: print("Move down") elif k == key.LEFT: print("Move left") elif k == key.RIGHT: print("Move right") # Catch interrupts try: while True: k = readkey() print(f"Pressed: {repr(k)}") except KeyboardInterrupt: print("User pressed CTRL+C") ``` ### POSIX Implementation Details On POSIX systems, the function reads characters and examines escape sequences: 1. Read first character (`c1`) 2. If it matches an interrupt key, raise `KeyboardInterrupt` 3. If not an escape (`\x1B`), return it immediately 4. If escape, read second character (`c2`) 5. Continue reading up to 5 total characters to complete multi-byte sequences 6. Return the complete sequence The POSIX implementation supports: - Single characters and ASCII characters - CTRL combinations (transmitted as control codes) - ANSI escape sequences for arrows, function keys, navigation keys - ALT combinations - CTRL+ALT combinations ### Windows Implementation Details On Windows, the function reads characters and examines scan codes: 1. Read first character 2. If it matches an interrupt key, raise `KeyboardInterrupt` 3. If it is a prefix byte (`\x00` or `\xe0`), read the scan code and return `\x00` + scan code 4. Handle UTF-16 surrogates for wide characters 5. Return the complete key sequence The Windows implementation supports: - Single characters and wide characters - CTRL combinations - Windows scan codes for special keys (arrows, function keys, navigation keys) - UTF-16 surrogate pairs for extended Unicode characters ### Source - `readchar/_posix_read.py:30-55` (POSIX implementation) - `readchar/_win_read.py:14-41` (Windows implementation) ### See Also - `readchar()` — For reading individual characters without escape sequence handling - `key` module — For key constants representing special keys - `config` class — For modifying `INTERRUPT_KEYS` behavior ```