argparse.ArgumentParser()
时间: 2023-10-14 12:13:10 浏览: 34
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.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![sb3](https://img-home.csdnimg.cn/images/20210720083646.png)