Advanced·12 min·engineering · cli · argparse
Building CLI tools with argparse
argparse: from script to tool
Any .py file becomes a real CLI with a few lines of argparse. Users get --help for free.
The four kinds of arguments
- Positional:
add_argument("name")— required, no dashes. - Optional:
add_argument("-l", "--lang")— dash-prefixed. - Flags:
add_argument("--shout", action="store_true")— presence = True. - Choices:
choices=["en","hi"]— argparse rejects anything else with a nice error.
Type coercion
type=int (or float, or your own function) parses + validates. Bad input → clean error, no traceback.
Making it installable
Add to pyproject.toml:
[project.scripts]
pygreet = "pygreet:main"
Then pip install . and pygreet Nitesh --lang hi works from anywhere.
Sub-commands (git-style)
sub = parser.add_subparsers(dest="cmd", required=True)
p_run = sub.add_parser("run", help="run something")
p_run.add_argument("--verbose", action="store_true")
p_deploy = sub.add_parser("deploy", help="deploy something")
p_deploy.add_argument("env")
Enables mytool run --verbose and mytool deploy prod.
When argparse isn't enough
- click — more ergonomic decorators.
- typer — click but with type hints, made by the FastAPI author.
- rich for pretty output, questionary for interactive prompts.
Try it
- Add a
--emojiflag that appends 👋. - Add a positional list arg for multiple names.