argparse.ArgumentParser()
时间: 2023-10-14 13:13:10 浏览: 83
arg_parser 源码
The `argparse.ArgumentParser()` function creates a new ArgumentParser object that can be used to parse command-line arguments.
The `ArgumentParser` class provides a flexible way to handle command-line arguments. It understands the conventional syntax for command-line options, and provides a simple interface for defining new options and arguments.
Here is an example of how to use it:
```
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
```
In this example, we create an `ArgumentParser` object, and define two arguments: `integers` and `--sum`. The `integers` argument is a positional argument, meaning that it doesn't start with a `-` or `--`. It takes an integer value, and it can take multiple values. The `--sum` argument is a named argument, meaning that it starts with `--`. It doesn't take any value, but when it is present, it changes the behavior of the program.
After defining the arguments, we call the `parse_args()` method to parse the command-line arguments. The `args` variable contains the parsed arguments. Finally, we use the `args` object to perform some operation. In this case, we call either the `sum` or `max` function on the `integers` argument, depending on whether the `--sum` argument was present or not.
阅读全文