0
# Console Interface
1
2
Command-line interface and text-based output methods for generating QR codes directly in terminals, saving to files, and displaying QR codes using ASCII characters or TTY colors.
3
4
## Capabilities
5
6
### Command Line Tool
7
8
The `qr` command provides full QR code generation from the command line with support for all image formats and output options.
9
10
```bash
11
# Basic usage
12
qr "Hello World" > qrcode.png
13
14
# Specify output file
15
qr "Hello World" --output qrcode.png
16
17
# Different image formats
18
qr "Hello World" --factory svg > qrcode.svg
19
qr "Hello World" --factory png > qrcode.png
20
qr "Hello World" --factory pil > qrcode.png
21
22
# Error correction levels
23
qr "Hello World" --error-correction L > qrcode_low.png # Low (7%)
24
qr "Hello World" --error-correction M > qrcode_med.png # Medium (15%, default)
25
qr "Hello World" --error-correction Q > qrcode_q.png # Quartile (25%)
26
qr "Hello World" --error-correction H > qrcode_high.png # High (30%)
27
28
# ASCII output to terminal
29
qr "Hello World" --ascii
30
31
# Read from stdin
32
echo "Hello World" | qr > qrcode.png
33
cat data.txt | qr --output qrcode.png
34
```
35
36
### Main Function
37
38
The main entry point for the command-line interface.
39
40
```python { .api }
41
from qrcode.console_scripts import main
42
43
def main(args=None):
44
"""
45
Main entry point for the qr command-line tool.
46
47
Parameters:
48
- args (list or None): Command line arguments, None to use sys.argv
49
50
Features:
51
- Automatic format detection based on output
52
- TTY vs file output handling
53
- Multiple image factory support
54
- Error correction level selection
55
- Data optimization options
56
"""
57
```
58
59
**Usage Example:**
60
61
```python
62
from qrcode.console_scripts import main
63
64
# Programmatic command-line interface
65
main(['Hello World', '--output', 'test.png'])
66
main(['--factory', 'svg', 'Hello SVG', '--output', 'test.svg'])
67
main(['--ascii', 'Terminal QR'])
68
```
69
70
### ASCII Terminal Output
71
72
Methods for displaying QR codes directly in the terminal using ASCII characters.
73
74
```python { .api }
75
class QRCode:
76
def print_ascii(self, out=None, tty=False, invert=False):
77
"""
78
Print QR code using ASCII characters.
79
80
Parameters:
81
- out (file-like or None): Output stream, defaults to sys.stdout
82
- tty (bool): Force TTY color mode
83
- invert (bool): Invert colors (solid <-> transparent)
84
85
Notes:
86
- Uses Unicode block characters for better display
87
- Automatically inverts colors for TTY mode
88
- Raises OSError if tty=True but output is not a TTY
89
"""
90
```
91
92
**Usage Example:**
93
94
```python
95
import qrcode
96
import sys
97
98
qr = qrcode.QRCode()
99
qr.add_data('Hello ASCII')
100
qr.make()
101
102
# Print to terminal
103
qr.print_ascii()
104
105
# Print with color inversion
106
qr.print_ascii(invert=True)
107
108
# Print to file
109
with open('ascii_qr.txt', 'w') as f:
110
qr.print_ascii(out=f)
111
112
# Force TTY colors (if terminal supports it)
113
if sys.stdout.isatty():
114
qr.print_ascii(tty=True)
115
```
116
117
### TTY Color Output
118
119
Enhanced terminal output using ANSI color codes for better visibility.
120
121
```python { .api }
122
class QRCode:
123
def print_tty(self, out=None):
124
"""
125
Print QR code using TTY colors (ANSI escape codes).
126
127
Parameters:
128
- out (file-like or None): Output stream, defaults to sys.stdout
129
130
Notes:
131
- Uses ANSI escape codes for black/white blocks
132
- Only works on TTY terminals
133
- Raises OSError if output is not a TTY
134
- Better visibility than ASCII on supported terminals
135
"""
136
```
137
138
**Usage Example:**
139
140
```python
141
import qrcode
142
import sys
143
144
qr = qrcode.QRCode()
145
qr.add_data('Hello TTY')
146
qr.make()
147
148
# Print with TTY colors (only if terminal supports it)
149
if sys.stdout.isatty():
150
try:
151
qr.print_tty()
152
except OSError:
153
print("TTY colors not supported")
154
qr.print_ascii()
155
else:
156
print("Not a TTY, using ASCII")
157
qr.print_ascii()
158
```
159
160
### Matrix Data Access
161
162
Methods for accessing raw QR code matrix data for custom output formats.
163
164
```python { .api }
165
class QRCode:
166
def get_matrix(self):
167
"""
168
Get the QR code as a 2D boolean matrix.
169
170
Returns:
171
List[List[bool]]: 2D matrix where True = black module, False = white
172
173
Notes:
174
- Includes border if border > 0
175
- Set border=0 for matrix without border
176
- Must call make() first
177
"""
178
```
179
180
**Usage Example:**
181
182
```python
183
import qrcode
184
185
qr = qrcode.QRCode(border=2)
186
qr.add_data('Matrix Data')
187
qr.make()
188
189
matrix = qr.get_matrix()
190
191
# Custom ASCII output
192
for row in matrix:
193
print(''.join('██' if cell else ' ' for cell in row))
194
195
# Export as CSV
196
import csv
197
with open('qr_matrix.csv', 'w', newline='') as f:
198
writer = csv.writer(f)
199
for row in matrix:
200
writer.writerow([1 if cell else 0 for cell in row])
201
202
# Convert to numpy array
203
import numpy as np
204
np_matrix = np.array(matrix, dtype=int)
205
print(f"QR code dimensions: {np_matrix.shape}")
206
```
207
208
### Factory Selection for Console
209
210
Command-line factory selection and available factories.
211
212
```python { .api }
213
# Built-in factory shortcuts for command line
214
default_factories = {
215
"pil": "qrcode.image.pil.PilImage",
216
"png": "qrcode.image.pure.PyPNGImage",
217
"svg": "qrcode.image.svg.SvgImage",
218
"svg-fragment": "qrcode.image.svg.SvgFragmentImage",
219
"svg-path": "qrcode.image.svg.SvgPathImage",
220
}
221
222
# Error correction mapping for command line
223
error_correction = {
224
"L": qrcode.ERROR_CORRECT_L, # ~7%
225
"M": qrcode.ERROR_CORRECT_M, # ~15% (default)
226
"Q": qrcode.ERROR_CORRECT_Q, # ~25%
227
"H": qrcode.ERROR_CORRECT_H, # ~30%
228
}
229
```
230
231
**Command Line Examples:**
232
233
```bash
234
# Use different factories
235
qr "Hello" --factory pil --output image.png
236
qr "Hello" --factory svg --output image.svg
237
qr "Hello" --factory svg-path --output compact.svg
238
qr "Hello" --factory png --output pure.png
239
240
# Error correction levels
241
qr "Hello" --error-correction L --output low_ec.png
242
qr "Hello" --error-correction H --output high_ec.png
243
244
# Optimization settings
245
qr "Hello123ABC" --optimize 5 --output optimized.png
246
qr "Long text data" --optimize 0 --output unoptimized.png # Disable optimization
247
```
248
249
### Cross-Platform Terminal Support
250
251
Automatic handling of terminal differences across operating systems.
252
253
```python { .api }
254
# Windows terminal color support
255
import sys
256
if sys.platform.startswith(("win", "cygwin")):
257
import colorama
258
colorama.init() # Automatically initialized for Windows
259
```
260
261
**Platform-Specific Behavior:**
262
263
- **Windows**: Automatically initializes colorama for ANSI color support
264
- **Unix/Linux/macOS**: Uses native ANSI color support
265
- **All platforms**: Falls back to ASCII if colors not supported
266
267
**Usage Example:**
268
269
```python
270
import qrcode
271
import sys
272
273
qr = qrcode.QRCode()
274
qr.add_data('Cross Platform')
275
qr.make()
276
277
# Smart terminal detection
278
if sys.stdout.isatty():
279
try:
280
qr.print_tty() # Try color output first
281
except OSError:
282
qr.print_ascii(tty=True) # Fall back to ASCII with TTY formatting
283
else:
284
# File output or pipe
285
if hasattr(sys.stdout, 'buffer'):
286
# Binary output (image)
287
img = qr.make_image()
288
img.save(sys.stdout.buffer)
289
else:
290
# Text output
291
qr.print_ascii()
292
```
293
294
### Output Format Detection
295
296
Automatic format detection based on output destination and parameters.
297
298
```python { .api }
299
# Automatic output format selection logic:
300
# 1. If --ascii flag: ASCII text output
301
# 2. If stdout is TTY: ASCII or TTY color output
302
# 3. If stdout is pipe/file: Image binary output
303
# 4. If --output specified: Save to file
304
305
def auto_output_format(output_file, is_tty, ascii_mode, image_factory):
306
"""
307
Determine output format based on context.
308
309
Parameters:
310
- output_file (str or None): Specified output file
311
- is_tty (bool): Whether stdout is a terminal
312
- ascii_mode (bool): Force ASCII mode
313
- image_factory: Selected image factory
314
315
Returns:
316
str: Output mode ('ascii', 'tty', 'image')
317
"""
318
```
319
320
**Format Selection Examples:**
321
322
```bash
323
# ASCII to terminal (detected automatically)
324
qr "Hello"
325
# Output: ASCII art to terminal
326
327
# Force ASCII even when piping
328
qr "Hello" --ascii > output.txt
329
# Output: ASCII art to file
330
331
# Image to file
332
qr "Hello" --output image.png
333
# Output: PNG image file
334
335
# Image to stdout (pipe)
336
qr "Hello" > image.png
337
# Output: Binary image data to stdout
338
339
# SVG to stdout
340
qr "Hello" --factory svg
341
# Output: SVG text to stdout
342
```