argparse 总结

mac2026-04-03  7

从简单的入手

# myfile.py import argparse parser = argparse.ArgumentParser() # 初始化 args = parser.parse_arg() # 只有-h, -help两个参数

输出:

# 命令行输入 python myfile.py --help # 输出 usage:myfile.py [-h] optional arguments: -h, --help show this help message and exit

开始加东西

# myfile.py import argparse parser = argparse.ArgumentParser(description='Myfile.py is a testing file') # grop 是互斥组,也即里面添加的参数最多只能出现一个 group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--network-path', metavar='NETWORK', help="pretrained network or network path (destination where network is saved)") # metavar参数 - 在 usage 说明中的参数名称,对于必选参数默认就是参数名称,对于可选参数默认是全大写的参数名称 # help参数 - 在输入-h或者--help时会显示的这个--network-path的帮助信息 group.add_argument('--network-offtheshelf', metavar='NETWORK', help="off-the-shelf network") # default, 当没有给出参数时,default为默认的参数 parser.add_argument('--datasets', metavar='DATASETS', default='oxford5k,paris6k', help="comma separated list of test datasets"# GPU ID,默认是 0 # ‘-g’ 短参数 parser.add_argument('--gpu-id', '-g', default='0', metavar='N', help="gpu id used for testing (default: '0')") args = parser.parse_arg()

来看看输出:

# 命令行输入 python myfile.py --help # 输出 # 注意看这里group组添加的参数中是最多只能选一个的模样 usage: myfile.py [-h](--network-path NETWORK | --network-offtheshelf NETWORK)[--dataset DATASET][--gpu-id N] Myfile.py is a testing file optional arguments: -h, --help show this help message and exit --network-path NETWORK pretrained network or network path (destination where network is save) --network-offtheshelf NETWORK off-the-shelf network --datasets DATASETS comma separated list of test datasets # 注意这里有个短参数的用法 --gup-id N,-g N gpu id used for testing (default: '0')
最新回复(0)