jsonargparse is a Python library that extends `argparse` to simplify the creation of Command-Line Interfaces (CLIs) and make Python applications easily configurable. It allows parsing configuration options from command line arguments, config files (JSON, YAML, Jsonnet, TOML), and environment variables, leveraging type hints for validation. It is a well-maintained project with frequent releases, adhering to high standards of development, including semantic versioning, deprecation periods, changelog, automated testing, and full test coverage.
pip install jsonargparseVerified import paths — ran on the pinned version, not inferred.
The simplest way to create a CLI is by using the `CLI()` function with a type-hinted Python function. `jsonargparse` automatically generates arguments, validates types, and uses docstrings for help messages.
If you relied on the `argparse`-like default exit-on-error behavior, you can re-enable it by setting `error_handler=usage_and_exit_error_handler` during `ArgumentParser` instantiation. For `error_handler` and `formatter_class`, pass callable objects directly instead of strings.
Update imports and class references from `SimpleNamespace` to `Namespace`. Ensure your code handles `Namespace` objects appropriately for parsed arguments.
For boolean arguments, use `parser.add_argument('--flag', action=ActionYesNo)` or `type=bool` with a default value, which `jsonargparse` handles correctly with `--flag`, `--no-flag`, or environment variables like `FLAG=true/false`.Design your CLIs to have all arguments explicitly defined or use subcommands. If you truly need to ignore unknown arguments, you might need to process `sys.argv` manually before passing to `jsonargparse` or implement custom parsing logic, but this is generally discouraged for robust applications.
To enable environment variable parsing for `parse_args()`, initialize your parser with `ArgumentParser(default_env=True)`. Alternatively, use `parser.parse_env()` to parse only environment variables.
Review the argument's type hint and the input value to ensure they are compatible. Adjust the input value or the argument definition as needed.
Ensure the specified file or directory exists and possesses the necessary read/write permissions matching the `Path_` type used in the argument definition (e.g., `Path_fr` for readable file, `Path_dw` for writeable directory).
Install `jsonargparse` with the `jsonschema` extra: `pip install "jsonargparse[jsonschema]"` or `pip install "jsonargparse[all]"` if other optional features are also needed.
Examine the `parser.add_argument()` call for the argument specified in the error message, verifying type hints, default values, and valid parameters. If it's a runtime error, ensure all required arguments are provided.