Parse command-line arguments with argparse in Python
======
Use the argparse module to enable options in your Python applications.
![Python options][1]
There are several third-party libraries for command-line argument parsing, but the standard library module `argparse`is no slouch either.
Without adding any more dependencies, you can write a nifty command-line tool with useful argument parsing.
### Argument parsing in Python
When parsing command-line arguments with `argparse`, the first step is to configure an `ArgumentParser`object. This is often done at the global module scope since merely _configuring_the parser has no side effects.
```
import argparse
PARSER = argparse.ArgumentParser()
```
The most important method on`ArgumentParser`is `.add_argument()`. It has a few variants. By default, it adds an argument that expects a value.
```
`PARSER.add_argument("--value")`
```
To see it in action, call the method `.parse_args()`:
There are more types of arguments available. The two most popular ones, after the default, are boolean and counting. The booleans come with a variant that defaults to true, and one that defaults to false.
This means that `active` is `False`unless `--active`is passed, and `dry_run` is `True`unless `--no-dry-run`is passed. Short options without value can be juxtaposed.
Passing all the arguments results in a non-default state:
In this case, running the command is done with `python -m my_package`. Alternatively, you can use the [`console_scripts`][2]entry points in the package's setup.
### Summary
The `argparse`module is a powerful command-line argument parser. There are many more features that have not been covered here. The limit is your imagination.