argparse is Python's standard library module for parsing command-line arguments. It simplifies the creation of user-friendly command-line interfaces by allowing programs to define required arguments and options, automatically generating help messages, and handling argument parsing and validation. It has been part of the standard library since Python 2.7 and 3.2. The PyPI package (version 1.4.0) is a backport primarily for older Python versions (< 2.7 or < 3.2) and is currently archived.
pip install argparseVerified import paths — ran on the pinned version, not inferred.
This quickstart defines a basic command-line tool that takes a required 'name' argument and an optional '--verbose' flag. It demonstrates creating an `ArgumentParser`, adding arguments, and parsing them.
Do not `pip install argparse` on modern Python versions; simply `import argparse`. If targeting older Python versions, explicitly install the PyPI backport.
Use `parser.add_argument('arg_name', type=int, help='...')` or `type=float` for automatic type conversion and basic validation.To customize this behavior, you can subclass `ArgumentParser` and override the `exit()` or `_print_message()` methods. Alternatively, for simple cases, `parser.parse_args(args=['--help'])` will still exit, but `parser.parse_known_args()` can be used to process only recognized arguments and return the rest.
Instead of `nargs=REMAINDER`, consider using `parser.parse_known_args()` to separate known arguments from unrecognized ones, and then process the 'unknown' arguments manually if needed.
New projects should use `argparse`. For existing `optparse` code, review the 'Upgrading Optparse Code' section in the `argparse` documentation for migration guidance, as direct compatibility is not always maintained.
Users can typically resolve this by preceding such values with a special `--` argument, which tells `argparse` to stop processing options and treat everything that follows as positional arguments. For specific arguments, you can also adjust `parser.prefix_chars` if appropriate, or use `nargs` and a custom type if dealing with very specific formats.
Ensure all required arguments are provided when invoking the script. For optional positional arguments, use `nargs='?'` or provide a `default` value in `add_argument()`.
Ensure all required positional arguments are provided on the command line. If an argument should be optional, define it with `nargs='?'` or provide a `default` value.
Ensure that all inputs for integer arguments are valid integers.
Verify that all provided arguments are defined in the parser and correctly spelled.
Include all required arguments when running the program.
Provide a value that is within the allowed choices for the argument.
Ensure that the value provided for the argument is a valid integer.
No dependency data recorded yet.