CLI¶
The mypackage console script. See the CLI guide for
usage, flags, and exit codes.
cli
¶
Command-line interface for mypackage.
Installed as the mypackage console script via the [project.scripts]
entry point in pyproject.toml:
mypackage summarize data.txt
mypackage smooth data.txt --method median --window 5
echo "1 2 3 4 5" | mypackage summarize - --json
The whole CLI is built on argparse from the standard library, so the package
still declares zero runtime dependencies. main returns
an exit status rather than calling sys.exit, which makes it directly
testable.
main
¶
main(argv: Sequence[str] | None = None, *, out: TextIO | None = None, err: TextIO | None = None, stdin: TextIO | None = None) -> int
Run the command-line interface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
argv
|
Sequence[str] | None
|
Argument list, excluding the program name. Defaults to
|
None
|
out
|
TextIO | None
|
Stream for normal output, including |
None
|
err
|
TextIO | None
|
Stream for error messages, including argparse usage errors.
Defaults to |
None
|
stdin
|
TextIO | None
|
Stream used when the input path is |
None
|
Returns:
| Type | Description |
|---|---|
int
|
|
int
|
a usage error (propagated from |
Examples:
>>> import io
>>> buffer = io.StringIO()
>>> main(
... ["summarize", "-", "--json"],
... out=buffer,
... stdin=io.StringIO("1 2 3 4"),
... )
0
>>> json.loads(buffer.getvalue())["mean"]
2.5
Source code in src/mypackage/cli.py
build_parser
¶
Build the top-level argument parser.
Exposed separately from main so documentation
tooling and tests can introspect the CLI without running it.
Returns:
| Type | Description |
|---|---|
ArgumentParser
|
A fully configured |
Examples:
>>> parser = build_parser()
>>> args = parser.parse_args(["summarize", "data.txt"])
>>> args.command, args.path, args.json
('summarize', 'data.txt', False)
Source code in src/mypackage/cli.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | |