0
# Command Line Interface
1
2
Command-line tools for generating documentation, running development servers, and integrating pdoc3 into build systems and workflows.
3
4
## Capabilities
5
6
### Main CLI Entry Point
7
8
Primary command-line interface with comprehensive argument parsing and processing.
9
10
```python { .api }
11
def main(_args=None) -> None:
12
"""
13
Command-line entry point for pdoc3.
14
15
Parameters:
16
- _args: Optional list of command line arguments (defaults to sys.argv)
17
18
Supports modes:
19
- HTML generation (--html)
20
- PDF/Markdown generation (--pdf)
21
- HTTP development server (--http)
22
- Text output (default)
23
"""
24
```
25
26
### Development Web Server
27
28
Built-in HTTP server for real-time documentation preview during development.
29
30
```python { .api }
31
class _WebDoc(BaseHTTPRequestHandler):
32
def do_GET(self):
33
"""
34
Handle GET requests for documentation pages.
35
36
Features:
37
- Live reload on file changes
38
- Module import path resolution
39
- Template rendering with error handling
40
- Search functionality
41
"""
42
43
def do_HEAD(self):
44
"""
45
Handle HEAD requests with ETag support for caching.
46
47
Returns:
48
- 200: Page exists and is current
49
- 304: Page unchanged (ETag match)
50
- 404: Module not found
51
- 205: Page modified, needs refresh
52
"""
53
54
def html(self) -> str:
55
"""
56
Generate HTML for the requested documentation page.
57
58
Returns:
59
str: Rendered HTML documentation
60
"""
61
62
def resolve_ext(self, import_path: str) -> str:
63
"""
64
Resolve external documentation links.
65
66
Parameters:
67
- import_path: Module import path
68
69
Returns:
70
str: Resolved external URL or local path
71
"""
72
73
# Class properties
74
args: argparse.Namespace # Command line arguments
75
template_config: Dict[str, Any] # Template configuration
76
```
77
78
### File System Operations
79
80
Functions for organizing and writing documentation files to the filesystem.
81
82
```python { .api }
83
def module_path(m: 'Module', ext: str) -> str:
84
"""
85
Get filesystem path for module documentation output.
86
87
Parameters:
88
- m: Module documentation object
89
- ext: File extension ('.html', '.md', etc.)
90
91
Returns:
92
str: Output file path
93
"""
94
95
def recursive_write_files(m: 'Module', ext: str, **kwargs) -> None:
96
"""
97
Recursively write documentation files for module and submodules.
98
99
Parameters:
100
- m: Module documentation object
101
- ext: File extension for output files
102
- **kwargs: Template configuration options
103
104
Creates:
105
- Documentation files for module and all submodules
106
- Directory structure matching module hierarchy
107
- Index files for packages
108
"""
109
```
110
111
### Search Index Generation
112
113
Generate search indices for client-side documentation search functionality.
114
115
```python { .api }
116
def _generate_lunr_search(modules: List['Module'], index_docstrings: bool,
117
template_config: Dict[str, Any]) -> None:
118
"""
119
Generate Lunr.js search index for documentation.
120
121
Parameters:
122
- modules: List of module documentation objects
123
- index_docstrings: If True, include docstrings in search index
124
- template_config: Template configuration dictionary
125
126
Creates:
127
- search.js with Lunr.js search index
128
- Client-side search functionality
129
"""
130
```
131
132
### CLI Configuration
133
134
Global configuration objects and constants for command-line processing.
135
136
```python { .api }
137
# Argument parser with all command-line options
138
parser: argparse.ArgumentParser
139
140
# Global arguments namespace
141
args: argparse.Namespace
142
143
# Server defaults
144
DEFAULT_HOST: str = 'localhost'
145
DEFAULT_PORT: int = 8080
146
```
147
148
## Command Line Options
149
150
### Basic Usage
151
152
```bash
153
# Generate HTML documentation
154
pdoc mymodule --html
155
156
# Generate documentation for multiple modules
157
pdoc module1 module2 module3 --html --output-dir ./docs
158
159
# Generate plain text documentation (default)
160
pdoc mymodule
161
162
# Generate PDF-ready Markdown
163
pdoc mymodule --pdf > mymodule.md
164
```
165
166
### Development Server
167
168
```bash
169
# Start development server on default port (8080)
170
pdoc mymodule --http :
171
172
# Start server on custom host and port
173
pdoc mymodule --http localhost:3000
174
175
# Multiple modules with server
176
pdoc package1 package2 --http :8080
177
```
178
179
### Advanced Options
180
181
```bash
182
# Custom output directory
183
pdoc mymodule --html --output-dir ./documentation
184
185
# Force overwrite existing files
186
pdoc mymodule --html --force
187
188
# Custom template directory
189
pdoc mymodule --html --template-dir ./templates
190
191
# Filter documentation (case-sensitive)
192
pdoc mymodule --html --filter "public,api"
193
194
# Skip import errors and continue
195
pdoc problematic_module --html --skip-errors
196
197
# Close stdin before importing (for problematic modules)
198
pdoc mymodule --html --close-stdin
199
```
200
201
### Template Configuration
202
203
```bash
204
# Override template options via command line
205
pdoc mymodule --html -c show_source=True -c external_links=True
206
207
# Multiple configuration options
208
pdoc mymodule --html \
209
-c show_source=True \
210
-c latex_math=True \
211
-c google_search_query="site:mydocs.com" \
212
-c git_link_template="https://github.com/user/repo/blob/main/{path}#L{start_line}"
213
```
214
215
## Usage Examples
216
217
### Basic Documentation Generation
218
219
```python
220
from pdoc.cli import main
221
222
# Generate HTML documentation
223
main(['mypackage', '--html', '--output-dir', './docs'])
224
225
# Generate with custom configuration
226
main([
227
'mypackage',
228
'--html',
229
'--template-dir', './custom-templates',
230
'-c', 'show_source=True',
231
'-c', 'external_links=True'
232
])
233
```
234
235
### Development Workflow
236
237
```python
238
from pdoc.cli import main
239
import subprocess
240
241
# Start development server in background
242
def start_dev_server(modules, port=8080):
243
"""Start development server for documentation preview."""
244
args = modules + ['--http', f':{port}']
245
main(args)
246
247
# Generate final documentation
248
def build_docs(modules, output_dir='./docs'):
249
"""Build final HTML documentation."""
250
main(modules + ['--html', '--output-dir', output_dir, '--force'])
251
252
# Example usage
253
modules = ['mypackage.core', 'mypackage.utils', 'mypackage.api']
254
255
# Development
256
start_dev_server(modules, 8080)
257
258
# Production build
259
build_docs(modules, './dist/docs')
260
```
261
262
### Batch Processing
263
264
```python
265
from pdoc.cli import main
266
import os
267
268
def generate_all_docs(package_root, output_root):
269
"""Generate documentation for all Python packages in directory."""
270
271
for item in os.listdir(package_root):
272
package_path = os.path.join(package_root, item)
273
274
if os.path.isdir(package_path) and os.path.exists(os.path.join(package_path, '__init__.py')):
275
output_dir = os.path.join(output_root, item)
276
277
try:
278
main([
279
package_path,
280
'--html',
281
'--output-dir', output_dir,
282
'--force',
283
'--skip-errors'
284
])
285
print(f"Generated docs for {item}")
286
287
except Exception as e:
288
print(f"Failed to generate docs for {item}: {e}")
289
290
# Usage
291
generate_all_docs('./src/packages', './docs')
292
```
293
294
### Integration with Build Systems
295
296
```python
297
# setup.py integration
298
from setuptools import setup
299
from pdoc.cli import main
300
301
class BuildDocsCommand:
302
"""Custom command to build documentation."""
303
304
def run(self):
305
main([
306
'mypackage',
307
'--html',
308
'--output-dir', './docs',
309
'--template-dir', './doc-templates',
310
'-c', 'show_source=True'
311
])
312
313
# Makefile integration
314
def make_docs():
315
"""Function callable from Makefile."""
316
main([
317
'myproject',
318
'--html',
319
'--output-dir', './build/docs',
320
'--force'
321
])
322
323
if __name__ == '__main__':
324
make_docs()
325
```
326
327
### Error Handling and Debugging
328
329
```python
330
from pdoc.cli import main
331
import sys
332
333
def safe_generate_docs(modules, **kwargs):
334
"""Generate documentation with comprehensive error handling."""
335
336
base_args = ['--html', '--skip-errors']
337
338
# Add configuration options
339
for key, value in kwargs.items():
340
base_args.extend(['-c', f'{key}={value}'])
341
342
try:
343
main(modules + base_args)
344
return True
345
346
except Exception as e:
347
print(f"Documentation generation failed: {e}", file=sys.stderr)
348
return False
349
350
# Usage with fallback
351
success = safe_generate_docs(
352
['mypackage'],
353
output_dir='./docs',
354
show_source=True,
355
external_links=True
356
)
357
358
if not success:
359
print("Falling back to basic text documentation")
360
main(['mypackage']) # Generate plain text as fallback
361
```