Python命令行参数处理模块optparse使用详解
本文详细介绍Python中optparse模块的使用方法。该模块能自动生成符合Unix/Posix规范的帮助文档,通过add_option()定义选项,利用parse_args()解析参数。文章涵盖选项缩写、全拼及type、default等命名参数的配置,并提供完整代码示例展示如何获取options对象和positional arguments,适用于需要标准命令行交互的Python程序开发。
本文通过具体实例解析Python中用于处理命令行参数的optparse模块,供读者参考学习。
optparse是Python内置的命令行参数处理模块,具备自动生成程序帮助信息的功能。其功能强大且易于使用,能够方便地生成符合Unix/Posix规范的标准化命令行说明。
调用 add_option() 方法来添加选项,随后使用 parse_args() 函数来解析传入的命令行参数。
add_option()函数的参数说明
第一个参数代表选项的缩写形式,以单个中划线开头,例如-f或-d。缩写仅限单个字母,且可以使用大写字母。
第二个参数代表选项的全称,以两个中划线开头,例如--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是一个对象(类型为optparse.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程序设计有所帮助。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









