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

发布时间:2020-10-21 17:34:01 作者:-牧野-
来源:脚本之家 阅读:162

本文实例讲述了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程序设计有所帮助。

推荐阅读:
  1. python:xml模块用法-xml处理、修改、删除
  2. Python模块的定义,模块的导入,__name__用法实例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python 命令行参数 optpars

上一篇:Spring MVC+FastJson+Swagger集成的完整实例教程

下一篇:Java定时任务的三种实现方式

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》