Python 的 argparse
模块中的 set_defaults() 方法可用于指定命令行参数的默认值。当定了多个子解析器时,.set_defaults()
的参数 which
可指定用于该参数的子解析器名称。
使用示例
在下面的例子中,为解析器 parser 添加了三个参数:
- positional argument input_file
- optional argument –output-file,默认值为 output.txt
- flag argument –verbose
import argparse
# Set up the ArgumentParser object
parser = argparse.ArgumentParser()
# Add a positional argument
parser.add_argument('input_file', help='input file path')
# Add an optional argument with default value
parser.add_argument('--output-file', help='output file path', default='output.txt')
# Add a flag argument to enable verbose mode
parser.add_argument('--verbose', action='store_true', help='increase output verbosity')
# Set default value for another optional argument using set_defaults() method
parser.set_defaults(verbose=False) # 1
# Parse the command-line arguments
args = parser.parse_args()
# Check the values of the arguments
print(f'Input file path: {args.input_file}')
print(f'Output file path: {args.output_file}')
print(f'Verbose mode: {args.verbose}')
- 在
1
处,使用parser.set_defaults()
为参数 verbose 设置默认值为 False
positional argument 是必须提供值的参数,直接运行上面的程序,不提供任何参数则会报错:
usage: example.py [-h] [--output-file OUTPUT_FILE] [--verbose] input_file
example.py: error: the following arguments are required: input_file
仅提供 positional argument,运行程序:
$ python example.py input.txt
Input file path: input.txt
Output file path: output.txt
Verbose mode: False
提供 optional argument 和 flag argument,运行程序:
$ python example.py input.txt --output-file=output2.txt --verbose
Input file path: input.txt
Output file path: output2.txt
Verbose mode: True
在指定了 verbose 后,其默认值 False 就会被指定值覆盖。