Argh is a lightweight Python library that simplifies the creation of command-line interfaces (CLIs) by building on top of the `argparse` module. It allows developers to define CLI commands using plain Python functions, reducing boilerplate code and inferring arguments from function signatures and type annotations. The library is actively maintained, with regular releases, and is currently at version 0.31.3.
pip install arghVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to create a simple CLI application with a single command (`verify_paths`) that accepts a list of paths and an optional verbose flag. Argh automatically infers arguments and types from the function signature and annotations. Run the script with `python your_script.py path1.txt path2.csv --verbose`.
Explicitly use `@argh.arg` decorators for arguments where automatic type hint introspection is not desired, or adjust your function signatures to match the desired CLI behavior.
To retain the old behavior of mapping to an option, explicitly define the argument as keyword-only (e.g., `def func(foo, *, bar=None)`). For complex cases, explicitly specify `old_name_mapping_policy=True` in `dispatch_command` or `dispatch_commands` during the transition, though this will change in future versions.
Review affected function signatures and either make the argument keyword-only (e.g., `def func(foo, *, bar=None)`) or explicitly pass `old_name_mapping_policy=True` to `dispatch_command`/`dispatch_commands` if the legacy behavior is intended.
Remove usages of `@expects_obj` and rely on standard function signatures or `@arg` decorators. For help, use the standard `--help` flag instead of `help` as a positional command.
Upgrade to Argh v0.31.2 or later to ensure correct parsing of `List` and `Optional[List]` type hints.
pip install argh
Use 'argh.decorators.alias' instead of 'argh.alias'.
Ensure 'context_locals' is installed and compatible with your Python version.
Ensure that `argh.dispatch_commands` (or `parser.add_subparsers`) has a `dest` argument set to capture the sub-command's name, and then access the arguments from the correct attribute or check if the command exists. Example: `subparsers = parser.add_subparsers(dest='command')` and later `if args.command == 'my_command': ...`
Provide the required sub-command when executing the script, or, if the sub-command should be optional, ensure `subparsers.required = False` (which is the default in newer `argparse` versions) and handle the case where no sub-command is given. You might also need to explicitly set `dest` for subparsers.