How to use parser.add_argument in Python?
In Python, parser.add_argument is a method used to add command-line arguments to the ArgumentParser. Here is an example using the ArgumentParser class from the argparse library.
import argparse
# 创建ArgumentParser对象
parser = argparse.ArgumentParser()
# 添加位置参数
parser.add_argument("input", help="输入文件的路径")
parser.add_argument("output", help="输出文件的路径")
# 添加可选参数
parser.add_argument("-v", "--verbose", action="store_true", help="显示详细信息")
# 解析命令行参数
args = parser.parse_args()
# 使用解析后的参数
print("输入文件路径:", args.input)
print("输出文件路径:", args.output)
if args.verbose:
print("启用了详细信息模式")
In the example above, we created an ArgumentParser object named ‘parser’ and added positional arguments ‘input’ and ‘output’, as well as optional arguments ‘-v’ and ‘–verbose’, using the add_argument method. Each argument comes with a help message. Finally, we used the parse_args method to parse the command line arguments and stored the parsed arguments in the ‘args’ object.
You can run this script in the command line and provide the necessary parameters to test it. For example:
python script.py input.txt output.txt -v
This will generate:
输入文件路径: input.txt
输出文件路径: output.txt
启用了详细信息模式