argparse.ArgumentParser
时间: 2023-10-14 11:11:27 浏览: 135
argparse.ArgumentParser is a class in Python's argparse module that is used to create argument parsers. It provides a convenient way to define the arguments that a command-line tool should accept and automatically generates help and usage messages.
Here's an example of how to use the ArgumentParser class to define a command-line tool that accepts two arguments:
```python
import argparse
parser = argparse.ArgumentParser(description='A simple command-line tool')
parser.add_argument('arg1', help='The first argument')
parser.add_argument('arg2', help='The second argument')
args = parser.parse_args()
print('arg1:', args.arg1)
print('arg2:', args.arg2)
```
In this example, we create an ArgumentParser object with a description of our tool. We then add two arguments using the add_argument method, which takes a name for the argument and a help message. Finally, we call parse_args to parse the command-line arguments and store the results in the args object. We can then access the values of the arguments using dot notation (args.arg1 and args.arg2) and print them out.
The ArgumentParser class also provides many other options for defining arguments, such as specifying their types, default values, and whether they are required or optional.
阅读全文