0
# Readchar
1
2
A cross-platform Python library for reading single characters and keystrokes from stdin without requiring the user to press Enter. It provides immediate character response without buffering, making it ideal for building interactive command-line applications, terminal user interfaces, and console-based input systems.
3
4
## Package Information
5
6
- **Package Name**: readchar
7
- **Language**: Python
8
- **Installation**: `pip install readchar`
9
- **Python Versions**: 3.8+
10
- **Platforms**: Linux, Windows, macOS, FreeBSD, OpenBSD
11
12
## Core Imports
13
14
```python
15
import readchar
16
```
17
18
Import specific functions:
19
20
```python
21
from readchar import readchar, readkey, key, config
22
```
23
24
## Basic Usage
25
26
```python
27
import readchar
28
from readchar import key
29
30
# Read a single character
31
char = readchar.readchar()
32
print(f"You pressed: {char}")
33
34
# Read a complete keystroke (including special keys)
35
keystroke = readchar.readkey()
36
if keystroke == key.UP:
37
print("Up arrow pressed")
38
elif keystroke == key.ENTER:
39
print("Enter pressed")
40
elif keystroke == "q":
41
print("Q pressed")
42
```
43
44
Interactive example:
45
46
```python
47
from readchar import readkey, key
48
49
print("Press arrow keys to move, 'q' to quit:")
50
while True:
51
k = readkey()
52
if k == "q":
53
break
54
elif k == key.UP:
55
print("Moving up")
56
elif k == key.DOWN:
57
print("Moving down")
58
elif k == key.LEFT:
59
print("Moving left")
60
elif k == key.RIGHT:
61
print("Moving right")
62
elif k == key.ENTER:
63
print("Action!")
64
```
65
66
## Capabilities
67
68
### Character Reading
69
70
Reads single characters from stdin with immediate response, without waiting for Enter key.
71
72
```python { .api }
73
def readchar() -> str:
74
"""
75
Reads a single character from stdin, returning it as a string with length 1.
76
Blocks until a character is available.
77
78
Returns:
79
str: Single character string
80
81
Note:
82
Only returns single ASCII characters. For complete keystrokes including
83
multi-character escape sequences, use readkey().
84
"""
85
```
86
87
### Keystroke Reading
88
89
Reads complete keystrokes including multi-character escape sequences for special keys like arrows, function keys, and key combinations.
90
91
```python { .api }
92
def readkey() -> str:
93
"""
94
Reads the next keystroke from stdin, returning it as a string.
95
Blocks until a keystroke is available.
96
97
Returns:
98
str: Complete keystroke string, either:
99
- Single character for normal keys (a, Z, 9, space, etc.)
100
- Multi-character escape sequence for special keys (arrows, F1-F12, etc.)
101
- Control combinations (Ctrl+A, Alt+A, etc.)
102
103
Raises:
104
KeyboardInterrupt: When interrupt keys are pressed (default: Ctrl+C)
105
106
Note:
107
Multi-character sequences are platform-specific but abstracted through
108
the key module constants for cross-platform compatibility.
109
"""
110
```
111
112
### Key Constants
113
114
Platform-specific key constants for comparing against readkey() results. The constants are defined based on the operating system for full portability.
115
116
```python { .api }
117
# Access pattern
118
from readchar import key
119
120
# Common constants available on all platforms:
121
key.LF # Line feed (\n)
122
key.CR # Carriage return (\r)
123
key.SPACE # Space character
124
key.ESC # Escape key
125
key.TAB # Tab key
126
key.ENTER # Enter key (platform-specific alias)
127
key.BACKSPACE # Backspace key (platform-specific)
128
129
# Control key combinations - all available
130
key.CTRL_A # Ctrl+A
131
key.CTRL_B # Ctrl+B
132
key.CTRL_C # Ctrl+C (default interrupt key)
133
key.CTRL_D # Ctrl+D
134
key.CTRL_E # Ctrl+E
135
key.CTRL_F # Ctrl+F
136
key.CTRL_G # Ctrl+G
137
key.CTRL_H # Ctrl+H
138
key.CTRL_I # Ctrl+I (alias for TAB)
139
key.CTRL_J # Ctrl+J (alias for LF)
140
key.CTRL_K # Ctrl+K
141
key.CTRL_L # Ctrl+L
142
key.CTRL_M # Ctrl+M (alias for CR)
143
key.CTRL_N # Ctrl+N
144
key.CTRL_O # Ctrl+O
145
key.CTRL_P # Ctrl+P
146
key.CTRL_Q # Ctrl+Q
147
key.CTRL_R # Ctrl+R
148
key.CTRL_S # Ctrl+S
149
key.CTRL_T # Ctrl+T
150
key.CTRL_U # Ctrl+U
151
key.CTRL_V # Ctrl+V
152
key.CTRL_W # Ctrl+W
153
key.CTRL_X # Ctrl+X
154
key.CTRL_Y # Ctrl+Y
155
key.CTRL_Z # Ctrl+Z
156
157
# Arrow keys
158
key.UP # Up arrow
159
key.DOWN # Down arrow
160
key.LEFT # Left arrow
161
key.RIGHT # Right arrow
162
163
# Navigation keys
164
key.INSERT # Insert key
165
key.DELETE # Delete key (alias for SUPR)
166
key.SUPR # Delete key
167
key.HOME # Home key
168
key.END # End key
169
key.PAGE_UP # Page Up
170
key.PAGE_DOWN # Page Down
171
172
# Function keys - all available
173
key.F1 # F1 key
174
key.F2 # F2 key
175
key.F3 # F3 key
176
key.F4 # F4 key
177
key.F5 # F5 key
178
key.F6 # F6 key
179
key.F7 # F7 key
180
key.F8 # F8 key
181
key.F9 # F9 key
182
key.F10 # F10 key
183
key.F11 # F11 key
184
key.F12 # F12 key
185
186
# Platform-specific additional keys may be available
187
# POSIX systems (Linux/macOS/BSD):
188
key.SHIFT_TAB # Shift+Tab
189
key.ALT_A # Alt+A
190
key.CTRL_ALT_A # Ctrl+Alt+A
191
key.CTRL_ALT_SUPR # Ctrl+Alt+Delete
192
193
# Windows systems:
194
key.ESC_2 # Alternative escape sequence
195
key.ENTER_2 # Alternative enter sequence
196
```
197
198
### Configuration
199
200
Static configuration class for customizing library behavior, particularly interrupt key handling.
201
202
```python { .api }
203
class config:
204
"""
205
Static configuration class containing constants used throughout the library.
206
Cannot be instantiated - use class attributes directly.
207
208
Attributes:
209
INTERRUPT_KEYS (List[str]): List of keys that will cause readkey()
210
to raise KeyboardInterrupt.
211
Default: [key.CTRL_C]
212
"""
213
214
INTERRUPT_KEYS: List[str] # Keys that trigger KeyboardInterrupt
215
216
def __new__(cls):
217
"""Raises SyntaxError - instances cannot be created."""
218
raise SyntaxError("you can't create instances of this class")
219
```
220
221
Usage example:
222
223
```python
224
from readchar import readkey, key, config
225
226
# Customize interrupt keys
227
config.INTERRUPT_KEYS = [key.CTRL_C, key.ESC]
228
229
# Now both Ctrl+C and Esc will raise KeyboardInterrupt
230
try:
231
k = readkey()
232
except KeyboardInterrupt:
233
print("Interrupted!")
234
```
235
236
## Platform Behavior
237
238
The library automatically detects the platform and uses appropriate low-level system calls:
239
240
- **POSIX systems** (Linux, macOS, FreeBSD, OpenBSD): Uses `termios` for raw terminal input
241
- **Windows systems** (win32, cygwin): Uses `msvcrt.getwch()` for console input
242
- **Unsupported platforms**: Raises `NotImplementedError`
243
244
Key constants are defined differently per platform but provide consistent names for cross-platform compatibility. The same code works across all supported platforms without modification.
245
246
## Error Handling
247
248
- **KeyboardInterrupt**: Raised by `readkey()` when keys in `config.INTERRUPT_KEYS` are pressed (default: Ctrl+C)
249
- **NotImplementedError**: Raised on unsupported platforms
250
- **SyntaxError**: Raised when attempting to instantiate the `config` class
251
252
## Types
253
254
```python { .api }
255
from typing import List
256
257
# Module exports
258
__all__ = ["readchar", "readkey", "key", "config"]
259
260
# Type hints are included - functions return str
261
def readchar() -> str: ...
262
def readkey() -> str: ...
263
264
# Config attribute type
265
config.INTERRUPT_KEYS: List[str]
266
```