Python argparse: add_argument Complete Guide

parser.add_argument is a method in the argparse module used to add command line arguments. Here is a simple example:

import argparse

# 创建ArgumentParser对象
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 created an ArgumentParser object and added two command line arguments using the add_argument method. The first argument accepts one or more integers and is saved in the integers attribute. The second argument is an optional parameter –sum, which stores the sum function in the accumulate attribute using the store_const action. If this parameter is not provided, the default is to use the max function.

Finally, we use the parse_args method to parse command line arguments and print the results. You can add more command line arguments as needed and handle them as necessary.

bannerAds