python optparse模块学习

简介:

Python 有两个内建的模块用于处理命令行参数:

一个是 getopt,getopt只能简单处理 命令行参数。

另一个是 optparse,是一个能够让程式设计人员轻松设计出简单明了、易于使用、符合标准的Unix命令列程式的Python模块。生成使用和帮助信息。

下面是一个简单的示例脚本optparse_exampl_1.py:

[root@localhost python]# vim optparse_exampl_1.py

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env python
from  optparse  import  OptionParser
parser  =  OptionParser()
parser.add_option( "-f" "--file" , dest = "filename" ,
                   help = "write report to FILE" , metavar = "FILE" )
parser.add_option( "-q" "--quiet" ,
                   action = "store_false" , dest = "verbose" , default = True ,
                   help = "don't print status messages to stdout" )
                                                                                                                                                             
(options, args)  =  parser.parse_args()

现在你可以在命令行进行如下输入:

1
2
3
4
5
<yourscript> --file=outfile -q
<yourscript> -f outfile --quiet
<yourscript> --quiet --file outfile
<yourscript> -q -foutfile
<yourscript> -qfoutfile

上面这些命令是相同效果的。除此之外, optparse 还为我们自动生成命令行的帮助信息:

1
2
<yourscript>  - h
<yourscript>  - - help

optparse将打印脚本的选项和帮助信息:

1
2
3
4
5
6
7
[root@localhost python] # ./optparse_exampl_1.py -h
Usage: optparse_exampl_1.py [options]
                                                                                                                                              
Options:
   - h,  - - help             show this  help  message  and  exit
   - FILE - - file = FILE   write report to  FILE
   - q,  - - quiet           don't  print  status messages to stdout

下面简单介绍optparse的用法:
aptparse 在大多数情况下是相当灵活和强大的,本文介绍常见的optparse用法。
首先要导入OptionParser类,在主程序中要创建一个类:
1
2
3
from  optparse  import  OptionParser
[...]
parser  =  OptionParser()

现在可以定义命令行选项,基本语法是:

1
2
parser.add_option(opt_str, ...,
                   attr = value, ...)

每种选项各有一个或多个选项的字符串,比如 -f 或 --file,通常每个选项将有一个短选项和一个长选项。例如:

1
parser.add_option( "-f" "--file" , ...)

你可以自由定义为许多短选项和尽可能多的长选项(包括零),但是至少要有一个选项字符串整体。
最后,一旦你已经定义好了所有的命令行参数,调用 parse_args() 来解析程序的命令行:
1
(options, args)  =  parser.parse_args()
注: 你也可以传递一个命令行参数列表到 parse_args();否则,默认使用 sys.argv[:1]。
parse_args() 返回的两个值:
options,它是一个对象(optpars.Values),保存有命令行参数值。只要知道命令行参数名,如 file,就可以访问其对应的值: options.file 。
args,它是一个由 positional arguments 组成的列表。
了解选项操作:
action 是 parse_args() 方法的参数之一,它指示 optparse 当解析到一个命令行参数时该如何处理。actions 有一组固定的值可供选择,默认是’store ‘,表示将命令行参数值保存在 options 对象里。
示例:
1
2
3
4
5
parser.add_option( "-f" "--file" ,
action = "store" type = "string" , dest = "filename" )
args  =  [ "-f" "foo.txt" ]
(options, args)  =  parser.parse_args(args)
print  options.filename
最后将会打印出 “foo.txt”。
当 optparse 解析到’-f’,会继续解析后面的’foo.txt’,然后将’foo.txt’保存到 options.filename 里。当调用 parser.args() 后,options.filename 的值就为’foo.txt’。
你也可以指定 add_option() 方法中 type 参数为其它值,如 int 或者 float 等等:
1
parser.add_option( "-n" type = "int" , dest = "num" )

注意:这个选项没有长选项,长选项也是可选的,如果没有指定dest选项,将用命令行的参数名对options对象的值进行存取。store也有其他的两种形式: stort_true 和 store_false, 用于处理带命令行选项后面不带值的情况,例如: -v,-q等命令行参数。

1
2
parser.add_option( "-v" , action = "store_true" , dest = "verbose" )
parser.add_option( "-q" , action = "store_false" , dest = "verbose" )

这样的话,当解析到 ‘-v’,options.verbose 将被赋予 True 值,反之,解析到 ‘-q’,会被赋予 False 值。

其它的 actions 值还有:

store_const 、append 、count 、callback

默认值

parse_args() 方法提供了一个 default 参数用于设置默认值。如:

1
2
parser.add_option( "-v" , action = "store_true" , dest = "verbose" )
parser.add_option( "-q" , action = "store_false" , dest = "verbose" , default = True )

又或者使用set_defaults例如:

1
2
3
parser.set_defaults(verbose = True )
parser.add_option(...)
(options, args)  =  parser.parse_args()

程序生成帮助
optparse 另一个方便的功能是自动生成程序的帮助信息。你只需要为 add_option() 方法的 help 选项指定帮助信息文本:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
usage  =  "usage: %prog [options] arg1 arg2"
parser  =  OptionParser(usage = usage)
parser.add_option( "-v" "--verbose" ,
                   action = "store_true" , dest = "verbose" , default = True ,
                   help = "make lots of noise [default]" )
parser.add_option( "-q" "--quiet" ,
                   action = "store_false" , dest = "verbose" ,
                   help = "be vewwy quiet (I'm hunting wabbits)" )
parser.add_option( "-f" "--filename" ,
                   metavar = "FILE" help = "write output to FILE" )
parser.add_option( "-m" "--mode" ,
                   default = "intermediate" ,
                   help = "interaction mode: novice, intermediate, "
                        "or expert [default: %default]" )

当 optparse 解析到 -h 或者 –help 命令行参数时,会调用 parser.print_help() 打印程序的帮助信息:

1
2
3
4
5
6
7
8
9
10
Usage: <yourscript> [options] arg1 arg2
                                                       
Options:
   - h,  - - help             show this  help  message  and  exit
   - v,  - - verbose         make lots of noise [default]
   - q,  - - quiet           be vewwy quiet (I'm hunting wabbits)
   - FILE - - filename = FILE
                         write output to  FILE
   - m MODE,  - - mode = MODE  interaction mode: novice, intermediate,  or
                         expert [default: intermediate]

(注意:当脚本打印帮助信息后会退出,不会解析其他选项参数)
自定义程序使用方法:
1
usage  =  "usage: %prog [options] arg1 arg2"
这行信息会优先打印在程序的选项信息前。当中的 %prog,optparse 会以当前程序名的字符串来替代:如 os.path.basename.(sys.argv[0])。
如果用户没有提供自定义的使用方法信息,optparse 会默认使用: “usage: %prog [options]”。
用户在定义命令行参数的帮助信息时,不用担心换行带来的问题,optparse 会处理好这一切。
设置 add_option 方法中的 metavar 参数,有助于提醒用户,该命令行参数所期待的参数,如 metavar=“mode”:
1
- m MODE,  - - mode = MODE
注意: metavar 参数中的字符串会自动变为大写。
在 help 参数的帮助信息里使用 %default 可以插入该命令行参数的默认值。
如果程序有很多的命令行参数,你可能想为他们进行分组,这时可以使用  OptionGroup
1
2
3
4
5
group  =  OptionGroup(parser,  "Dangerous Options" ,
                     "Caution: use these options at your own risk.  "
                     "It is believed that some of them bite." )
group.add_option( "-g" , action = "store_true" help = "Group option." )
parser.add_option_group(group)

输出如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Usage: <yourscript> [options] arg1 arg2
                          
Options:
   - h,  - - help             show this  help  message  and  exit
   - v,  - - verbose         make lots of noise [default]
   - q,  - - quiet           be vewwy quiet (I'm hunting wabbits)
   - FILE - - filename = FILE
                         write output to  FILE
   - m MODE,  - - mode = MODE  interaction mode: novice, intermediate,  or
                         expert [default: intermediate]
                          
   Dangerous Options:
     Caution: use these options at your own risk.  It  is  believed that some
     of them bite.
                          
     - g                  Group option.

完整的列子:

1
2
3
4
5
6
7
8
9
10
11
12
13
group  =  OptionGroup(parser,  "Dangerous Options" ,
                     "Caution: use these options at your own risk.  "
                     "It is believed that some of them bite." )
group.add_option( "-g" , action = "store_true" help = "Group option." )
parser.add_option_group(group)
                     
group  =  OptionGroup(parser,  "Debug Options" )
group.add_option( "-d" "--debug" , action = "store_true" ,
                  help = "Print debug information" )
group.add_option( "-s" "--sql" , action = "store_true" ,
                  help = "Print all SQL statements executed" )
group.add_option( "-e" , action = "store_true" help = "Print every action done" )
parser.add_option_group(group)

本文转自1594cqb 51CTO博客,原文链接:http://blog.51cto.com/wolfchen/1230061,如需转载请自行联系原作者
相关文章
|
2天前
|
Python
【Python21天学习挑战赛】- 错误和异常
【Python21天学习挑战赛】- 错误和异常
|
2天前
|
容器
【Python21天学习挑战赛】-迭代器 & f-格式化 & 模块
【Python21天学习挑战赛】-迭代器 & f-格式化 & 模块
|
2天前
|
Python
【Python21天学习挑战赛】- 函数进阶
【Python21天学习挑战赛】- 函数进阶
|
2天前
【Python21天学习挑战赛】文件读写操作
【Python21天学习挑战赛】文件读写操作
|
2天前
|
索引 Python
【Python21天学习挑战赛】集合 & 数据类型补充
【Python21天学习挑战赛】集合 & 数据类型补充
|
2天前
|
存储 缓存 Python
【Python21天学习挑战赛】字典 && 小数据池
【Python21天学习挑战赛】字典 && 小数据池
|
2天前
|
存储 索引 Python
【Python21天学习挑战赛】-列表 & 元组 & range
【Python21天学习挑战赛】-列表 & 元组 & range
|
2天前
|
Python
【Python21天学习挑战赛】-入门必备
【Python21天学习挑战赛】-入门必备
|
2天前
|
关系型数据库 MySQL C语言
【Python21天学习挑战赛】—Day1:学习规划,我与python的相遇
【Python21天学习挑战赛】—Day1:学习规划,我与python的相遇
|
4天前
|
人工智能 安全 Java
Python 多线程编程实战:threading 模块的最佳实践
Python 多线程编程实战:threading 模块的最佳实践
119 5