optpars是python中用来处理命令行参数的模块,可以自动生成程序的帮助信息,功能强大,易于使用,可以方便的生成标准的,符合Unix/Posix 规范的命令行说明。

使用 add_option() 来加入选项,使用 parse_args() 来解析命令行。



add_option()中参数


第一个参数表示option的缩写,以单个中划线引导,例如-f、-d,只能用单个字母,可以使用大写;
第二个参数表示option的全拼,以两个中划线引导,例如--file、--Opencv_version;

第一第二个参数可以单独使用,也可以同时使用,但必须保证有其中一个;

从第三个参数开始是命名参数,是可选参数,常用的几个:

type=: 表示输入命令行参数的值的类型,默认为string,可以指定为string, int, choice, float,complex其中一种;
default=: 表示命令参数的默认值;
metavar=: 显示到帮助文档中用来提示用户输入期望的命令参数;
dest=:指定参数在options对象中成员的名称,如果没有指定dest参数,将用命令行参数名来对options对象的值进行存取。

help=:  显示在帮助文档中的信息;



解析命令行


(options, args) = parse.parse_args()

或在main(argv)函数里:

(options, args) = parser.parse_args(argv)
options,是一个对象(optpars.Values),保存有命令行参数值。通过命令行参数名,如 file,访问其对应的值: options.file ;
args,是一个由 positional arguments 组成的列表;


optparse使用


import sys
from optparse import OptionParser

parser = OptionParser()

parser.add_option('-f','--file',type=str,default='./image',help='file path of images',dest='file_path')
parser.add_option('--weights','-w',type=str,default='./weights_saved',help="file location of the trained network weights")
parser.add_option('--iterations','-i',type=int,default=10000,help='iteration time of CRNN Net')
parser.add_option('--gpu','-g',type=int,default=0,help="gpu id")


def main(argv):
    (options, args) = parser.parse_args()
    (options, args) = parser.parse_args(argv)   # both OK

    print 'file path of images:  ' + options.file_path
    print "file location of the trained network weights:  " + options.weights
    print 'iteration time of CRNN Net:  ' + str(options.iterations)
    print 'gpu id:  ' + str(options.gpu)


if __name__ == '__main__':
  main(sys.argv)

查看帮助文档:

python test.py -h

显示:

Usage: test.py [options]

Options:
  -h, --help            show this help message and exit
  -f FILE_PATH, --file=FILE_PATH
                        file path of images
  -w WEIGHTS, --weights=WEIGHTS
                        file location of the trained network weights
  -i ITERATIONS, --iterations=ITERATIONS
                        iteration time of CRNN Net
  -g GPU, --gpu=GPU     gpu id

输入命令行参数:

python test.py -f ../tensorflow/train_image -w ../tensorflow/weights -i 5000 -g 2

输出:

file path of images:  ../tensorflow/train_image
file location of the trained network weights:  ../tensorflow/weights
iteration time of CRNN Net:  5000
gpu id:  2

posted on 2018-03-09 12:32  未雨愁眸  阅读(219)  评论(0编辑  收藏  举报