argparse包的使用

2019-10-04  本文已影响0人  csuhan

最近接触的一些论文代码,基本都要配置训练、测试脚本,而难免需要在程序运行时指定配置文件、预训练模型等;相比于直接修改程序内定义的参数,采用argpaser能够更便捷的切换程序参数,却不需要考虑程序内部的结构。

argpaser包的用法也比较简单,使我们省去了解析命令行argv的过程。

# 1. 定义parser
import argparse
parser = argparse.ArgumentParser(description="R-CNN series model test program")
# 2. 添加参数
parser = argparse.ArgumentParser(description="R-CNN series model test program")
parser.add_argument('config',help='config file path')
parser.add_argument('checkpoint',help='checkpoint file path')
parser.add_argument('img',help='image path to be tested')
parser.add_argument('-b','--backbone',type=str,choices=['resnet','vgg'],default='resnet',help="backbone network type")
parser.add_argument('-gpus',type=str,default='0',help='list of gpu devices to use')
# 3. 解析命令
args = parser.parse_args()
print(args)

在运行时,如输入python arg_demo.py -h,则会输出程序用法:

usage: arg_demo.py [-h] [-b {resnet,vgg}] [-gpus GPUS] config checkpoint img

R-CNN series model test program

positional arguments:
  config                config file path
  checkpoint            checkpoint file path
  img                   image path to be tested

optional arguments:
  -h, --help            show this help message and exit
  -b {resnet,vgg}, --backbone {resnet,vgg}
                        backbone network type
  -gpus GPUS            list of gpu devices to use

而正确的用法:

python arg_demo.py config.py w.weights  demo.jpg -b resnet -gpus 0,1,2,3
上一篇 下一篇

猜你喜欢

热点阅读