企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
更新于2017年4月15日,下午 ## 概述 optparse用来解析命令行参数 #### 官方文档 https://docs.python.org/3/library/optparse.html #### 例子 ```python from optparse import OptionParser usage = "usage: %prog [options] arg1 arg2" version="%prog 1.0" parser = OptionParser(usage=usage, version=version) parser.add_option("-f", "--file", dest="filename", action="store", type="string", default="foo.txt") parser.add_option("-v", dest="verbose", action="store_true", default=True) args = ["-f", "foo.txt"] (options, args) = parser.parse_args(args) print options.filename ``` 当 optparse 解析到-f,会继续解析后面的foo.txt,然后将foo.txt保存到 options.filename 里。当调用 parser.args() 后,options.filename 的值就为foo.txt。 `add_option() `: 定义命令行参数 `parse_args()`: 返回的两个值 > **options**:它是一个对象(optpars.Values),**字典形式**保存选项和参数。 > **args**:它是一个由 positional arguments 组成的列表。 #### dest > **dest**参数也是可选的。如果没有指定 dest 参数,将用命令行的参数名来对 options 对象的值进行存取。 #### action > **action** 是 parse_args() 方法的参数之一,它指示 optparse 当解析到一个命令行参数时该如何处理。action 有一组固定的值可供选择,默认是`store`,表示将命令行参数值保存在 options 对象里。store_true 和 store_false 表示将参数保存到**args**中,并将对应选项的值相应设置为True或者False #### type > **type** 参数默认为string,如 int 或者 float #### default > **default** 参数用于设置默认值,可以使True或者False或者其他默认参数