【python】optparse

optparse python

首先,必须 import OptionParser 类,建立一个 OptionParser 对象: app

使用 add_option 来定义命令行参数:每一个命令行参数就是由参数名字符串和参数属性组成的。如 -f 或者 –file 分别是长短参数名: ui

最后,一旦你已经定义好了全部的命令行参数,调用 parse_args() 来解析程序的命令行:你也能够传递一个命令行参数列表到 parse_args();不然,默认使用 sys.argv[:1]。 this

parse_args() 返回的两个值: spa

  • options,它是一个对象(optpars.Values),保存有命令行参数值。只要知道命令行参数名,如 file,就能够访问其对应的值: options.file 。
  • args,它是一个由 positional arguments 组成的列表。

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()



<yourscript> --file=outfile -q  
<yourscript> -f outfile --quiet  
<yourscript> --quiet --file outfile  
<yourscript> -q -foutfile  
<yourscript> -qfoutfile



add_option()参数说明:

action:存储方式,分为三种store、store_false、store_true 命令行

action 是 parse_args() 方法的参数之一,它指示 optparse 当解析到一个命令行参数时该如何处理。actions 有一组固定的值可供选择,默认是’store ‘,表示将命令行参数值保存在 options 对象里 code

type:类型 对象

默认地,type 为’string’。也正如上面所示,长参数名也是可选的。其实,dest 参数也是可选的。若是没有指定 dest 参数,将用命令行的参数名来对 options 对象的值进行存取。 ip

store 也有其它的两种形式: store_true 和 store_false ,用于处理带命令行参数后面不带值的状况。如 -v,-q 等命令行参数:这样的话,当解析到 ‘-v’,options.verbose 将被赋予 True 值,反之,解析到 ‘-q’,会被赋予 False 值。 字符串

其它的 actions 值还有:store_const 、append 、count 、callback 。

   dest:存储的变量
   default:默认值
   help:帮助信息

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

<yourscript> -h  
<yourscript> --help  
#输出
usage: <yourscript> [options]  
  
options:  
  -h, --help            show this help message and exit  
  -f FILE, --file=FILE  write report to FILE  
  -q, --quiet           don't print status messages to stdout
相关文章
相关标签/搜索