当前位置: 移动技术网 > IT编程>脚本编程>Python > Python处理命令行参数模块optpars用法实例分析

Python处理命令行参数模块optpars用法实例分析

2018年08月20日  | 移动技术网IT编程  | 我要评论

信誉国际娱乐城,autopatch,极品娘子榜

本文实例讲述了python处理命令行参数模块optpars用法。分享给大家供大家参考,具体如下:

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

更多关于python相关内容感兴趣的读者可查看本站专题:《python数学运算技巧总结》、《python字符串操作技巧汇总》、《python编码操作技巧总结》、《python数据结构与算法教程》、《python函数使用技巧总结》、《python入门与进阶经典教程》及《python文件与目录操作技巧汇总

希望本文所述对大家python程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网