0
# CLI Interface
1
2
Command-line argument parsing and option handling with comprehensive configuration support for controlling dependency tree display and output formats.
3
4
## Capabilities
5
6
### Options Class
7
8
Configuration object containing all CLI options with type annotations.
9
10
```python { .api }
11
class Options(Namespace):
12
"""Namespace class containing all CLI configuration options."""
13
14
# Output format options
15
freeze: bool # Print in pip freeze format
16
json: bool # Output raw JSON
17
json_tree: bool # Output nested JSON tree
18
mermaid: bool # Output Mermaid diagram
19
output_format: str | None # GraphViz output format (dot, png, svg, etc.)
20
21
# Package selection options
22
python: str # Python interpreter path
23
path: list[str] # Custom search paths
24
packages: str # Comma-separated package list to show
25
exclude: str # Comma-separated package list to exclude
26
exclude_dependencies: bool # Exclude dependencies of excluded packages
27
all: bool # List all deps at top level
28
local_only: bool # Show only virtualenv packages
29
user_only: bool # Show only user site packages
30
31
# Display options
32
reverse: bool # Show reverse dependencies
33
depth: float # Limit tree depth
34
encoding: str # Output encoding
35
license: bool # Show package licenses
36
37
# Warning control
38
warn: WarningType # Warning level (silence/suppress/fail)
39
```
40
41
### Argument Parsing
42
43
Main functions for parsing command-line arguments.
44
45
```python { .api }
46
def get_options(args: Sequence[str] | None) -> Options:
47
"""
48
Parse command line arguments and return Options object.
49
50
Parameters:
51
- args: List of command line arguments (None uses sys.argv)
52
53
Returns:
54
Options object with parsed configuration
55
56
Raises:
57
SystemExit: If argument parsing fails or validation errors occur
58
"""
59
60
def build_parser() -> ArgumentParser:
61
"""
62
Build and configure the argument parser.
63
64
Returns:
65
Configured ArgumentParser instance with all pipdeptree options
66
"""
67
```
68
69
### Main Entry Point
70
71
CLI application entry point for command-line usage.
72
73
```python { .api }
74
def main(args: Sequence[str] | None = None) -> int | None:
75
"""
76
CLI - The main function called as entry point.
77
78
This function:
79
1. Parses command line arguments
80
2. Discovers installed packages
81
3. Builds dependency tree
82
4. Validates for conflicts/cycles
83
5. Renders output in requested format
84
85
Parameters:
86
- args: Command line arguments (None uses sys.argv)
87
88
Returns:
89
Exit code: 0 for success, 1 for errors/warnings (depending on warn setting)
90
"""
91
```
92
93
### Enum Action Handler
94
95
Custom argparse action for handling enum-based arguments.
96
97
```python { .api }
98
class EnumAction(Action):
99
"""
100
Generic action that converts string into Enum value for argparse.
101
102
Used for handling WarningType enum values from command line arguments.
103
"""
104
```
105
106
## Command Line Arguments
107
108
### Package Selection Arguments
109
110
```bash
111
# Interpreter and path options
112
--python PATH # Python interpreter to inspect (default: current)
113
--python auto # Auto-detect virtual environment
114
--path PATH # Restrict package search paths (can be used multiple times)
115
116
# Package filtering
117
-p, --packages PKG # Comma-separated packages to show (supports wildcards)
118
-e, --exclude PKG # Comma-separated packages to exclude (supports wildcards)
119
--exclude-dependencies # Also exclude dependencies of excluded packages
120
121
# Scope limiting
122
-l, --local-only # Only show virtualenv packages (if in virtualenv)
123
-u, --user-only # Only show user site directory packages
124
```
125
126
### Output Format Arguments
127
128
```bash
129
# Text output options
130
-a, --all # List all dependencies at top level
131
-d, --depth N # Limit tree depth to N levels
132
-r, --reverse # Show reverse dependencies
133
--license # Show package licenses
134
--encoding ENC # Set output encoding
135
136
# Alternative output formats
137
-f, --freeze # Output in pip freeze format
138
-j, --json # Output raw JSON
139
--json-tree # Output nested JSON tree
140
--mermaid # Output Mermaid flow diagram
141
--graph-output FMT # GraphViz output format (dot, png, svg, pdf, etc.)
142
```
143
144
### Warning Control Arguments
145
146
```bash
147
-w, --warn LEVEL # Warning control: silence, suppress (default), fail
148
```
149
150
### Informational Arguments
151
152
```bash
153
-v, --version # Show version information
154
-h, --help # Show help message
155
```
156
157
## Usage Examples
158
159
### Basic Usage
160
161
```python
162
from pipdeptree._cli import get_options, main
163
164
# Parse arguments programmatically
165
options = get_options(['--packages', 'django,requests', '--json'])
166
print(f"Output format: {'JSON' if options.json else 'text'}")
167
print(f"Packages: {options.packages}")
168
169
# Run full CLI pipeline
170
exit_code = main(['--reverse', '--packages', 'numpy'])
171
```
172
173
### Command Line Examples
174
175
```bash
176
# Show dependency tree for all packages
177
pipdeptree
178
179
# Show specific packages with wildcards
180
pipdeptree --packages "django*,requests"
181
182
# Show what depends on specific packages
183
pipdeptree --reverse --packages numpy,matplotlib
184
185
# Output formats
186
pipdeptree --json > deps.json
187
pipdeptree --json-tree > tree.json
188
pipdeptree --mermaid > deps.mmd
189
pipdeptree --graph-output png > deps.png
190
191
# Filtering and scoping
192
pipdeptree --local-only --exclude "test*,dev*"
193
pipdeptree --user-only --depth 2
194
195
# Environment and interpreter selection
196
pipdeptree --python /path/to/venv/bin/python
197
pipdeptree --python auto # Auto-detect virtual environment
198
199
# Warning control
200
pipdeptree --warn fail # Exit with code 1 if conflicts found
201
pipdeptree --warn silence # No warning output
202
```
203
204
### Integration with Other Functions
205
206
```python
207
from pipdeptree._cli import get_options
208
from pipdeptree._discovery import get_installed_distributions
209
from pipdeptree._models import PackageDAG
210
from pipdeptree._render import render
211
from pipdeptree._validate import validate
212
213
# Parse CLI options
214
options = get_options(['--json', '--packages', 'requests'])
215
216
# Use options to configure package discovery
217
distributions = get_installed_distributions(
218
interpreter=options.python,
219
supplied_paths=options.path or None,
220
local_only=options.local_only,
221
user_only=options.user_only,
222
)
223
224
# Build and filter tree
225
tree = PackageDAG.from_pkgs(distributions)
226
validate(tree)
227
228
if options.reverse:
229
tree = tree.reverse()
230
231
# Apply package filtering
232
if options.packages or options.exclude:
233
include = options.packages.split(",") if options.packages else None
234
exclude = set(options.exclude.split(",")) if options.exclude else None
235
tree = tree.filter_nodes(include, exclude, options.exclude_dependencies)
236
237
# Render output
238
render(options, tree)
239
```
240
241
## Argument Validation
242
243
The CLI performs several validation checks:
244
245
```python
246
# Mutual exclusion validation
247
if options.exclude_dependencies and not options.exclude:
248
parser.error("must use --exclude-dependencies with --exclude")
249
250
if options.license and options.freeze:
251
parser.error("cannot use --license with --freeze")
252
253
if options.path and (options.local_only or options.user_only):
254
parser.error("cannot use --path with --user-only or --local-only")
255
```
256
257
## Error Handling
258
259
The CLI handles various error conditions:
260
261
- **Invalid arguments**: Argument parser shows usage and exits
262
- **Interpreter query failures**: Returns exit code 1 with error message
263
- **Include/exclude conflicts**: Returns exit code 1 with conflict message
264
- **Pattern not found warnings**: Handled based on warning configuration
265
- **Dependency conflicts**: Exit code determined by warning level setting
266
267
## Custom Formatter
268
269
The CLI uses a custom help formatter for improved readability:
270
271
```python { .api }
272
class _Formatter(ArgumentDefaultsHelpFormatter):
273
"""Custom formatter with wider help display and better positioning."""
274
275
def __init__(self, prog: str) -> None:
276
super().__init__(prog, max_help_position=22, width=240)
277
```