argparse
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.
Warnings
- gotcha The `argparse` module is part of the Python standard library for versions 2.7 and 3.2 and later. The PyPI package `argparse` (version 1.4.0) is a backport primarily intended for older Python versions (e.g., Python < 2.7 or < 3.2) or specific older Python 3.x releases. For most modern Python users, `pip install argparse` is unnecessary and potentially problematic as you already have a built-in, possibly newer, version.
- gotcha By default, `argparse` treats all command-line inputs as strings. If you expect integer, float, or other types, you must explicitly specify the `type` argument in `add_argument()`. Failure to do so will result in string values, requiring manual conversion and validation in your code.
- gotcha When `argparse` encounters invalid arguments or requests for help, its default behavior is to print messages to `sys.stderr` and then exit the program using `sys.exit()`. This can be undesirable in applications where you want to handle errors programmatically or integrate argument parsing into a larger system without exiting.
- deprecated The `nargs=REMAINDER` action was removed from the official documentation due to its fragility and potential for unexpected behavior when interspersed with other options. While still functional, it's not recommended for new code.
- breaking The `optparse` module, a predecessor to `argparse`, was officially deprecated in Python 2.7+ and 3.2+ in favor of `argparse`. While `optparse` is still available, `argparse` offers more features and a different API, meaning direct replacements might require code changes.
- gotcha If an argument value itself starts with a hyphen (e.g., a negative number or a filename like `-output.txt`), `argparse` might misinterpret it as an optional argument or flag, leading to 'unrecognized argument' errors.
Install
-
pip install argparse -
# argparse is included in the Python standard library since 2.7 and 3.2. # No installation is typically required for modern Python versions.
Imports
- argparse
import argparse
Quickstart
import argparse
def main():
parser = argparse.ArgumentParser(
description='A simple command-line tool.'
)
parser.add_argument(
'name',
type=str,
help='The name to greet.'
)
parser.add_argument(
'-v', '--verbose',
action='store_true',
help='Enable verbose output.'
)
args = parser.parse_args()
if args.verbose:
print(f"Verbose mode enabled. Greeting {args.name}...")
print(f"Hello, {args.name}!")
if __name__ == '__main__':
main()