【Python 命令行参数解析: optparse 模块】
2017-08-29 19:31
633 查看
大家在使用Python进行脚本开发时,经常需要通过终端交互的方式对Python的脚本模块进行调用。这时在
Python模块中提供基础的命令行参数支持是必不可少的。那么,在Python中我们如何实现命令行参数的传入和解析呢,如下内容将对此进行简要的介绍。
两种内置支持
测试
在终端中输入如下命令,执行argv.py。
查看输出结果:
说明
action参数的取值默认为 store,表示把该命令行参数存储的options对象中。
store_true 和 store_false 一般用于只有命令没有值的情况。store_true 表示当该命令在命令行中出现时,将 dest 属性所定义的变量值设置为 true。 相应的, store_false 则表示当该命令在命令行中出现时,将 dest 属性所定义的变量值设置为 false.
用户可以通过opts.[dest指定的变量名] 来获得解析后的参数。
Python模块中提供基础的命令行参数支持是必不可少的。那么,在Python中我们如何实现命令行参数的传入和解析呢,如下内容将对此进行简要的介绍。
Python对命令行参数解析的支持
Python中通过两个内建模块对命令行参数解析进行支持:getopt 和 optparse两种内置支持
模块名 | 功能说明 |
---|---|
getopt | 对命令行参数进行简单的处理 |
optparse | 能够对命令行参数进行复杂的处理,并便捷生成类Unix的帮助信息,功能更为强大。 |
基本使用
示例代码:"""A simple usage example for optparse module By Fat Boy. """ from optparse import OptionParser # Import the module def main(): opts = parse_command() print("Param filename: " + opts.filename) print("Param Debug: " + str(opts.debug)) def parse_command(): parser = OptionParser() # Initialize the OptionParser class # Add commandline parameters format parser.add_option("-f", "--filename", dest="filename", help="Set the output file name") parser.add_option("-D", "--Debug", action="store_true", dest="debug", default=False, help="Set the debug switch") # Parse the command params (opts, args) = parser.parse_args() return opts if __name__ == "__main__": main()
测试
在终端中输入如下命令,执行argv.py。
python argv.py --file=outfile -D
查看输出结果:
Param filename: outfile Param Debug: True
关键方法介绍
基于 “optparse” 模块处理命令行参数时, “add_option()” 是最为重要的方法OptionParser 初始化
add_option()定义命令行参数
parser.add_option("-D", "--Debug", action="store_true", dest="debug", default=False, help="Set the debug switch")
参数名称 | 功能 | 说明 |
---|---|---|
参数0 | 第一个参数,命令行参数短名称 | 参考代码:“-D” |
参数1 | 第二个参数,命令行参数长名称 | 参考代码: “–Debug” |
action | 指示 optparse 当解析到一个命令行参数时该如何处理store、store_true、store_false、store_const 、append 、count 、callback | 默认为store |
dest | 设置存储参数值的变量名 | 存储的内容就是参数后面紧挨的内容 |
type | 设置参数的数据类型 | 默认为string,还可设置:int/float |
default | 设置参数的默认值 | |
help | 设置参数的帮助说明文字 | |
metavar | 用于提醒用户参数应输入的值 | 显示为大写 |
action参数的取值默认为 store,表示把该命令行参数存储的options对象中。
store_true 和 store_false 一般用于只有命令没有值的情况。store_true 表示当该命令在命令行中出现时,将 dest 属性所定义的变量值设置为 true。 相应的, store_false 则表示当该命令在命令行中出现时,将 dest 属性所定义的变量值设置为 false.
parse_args()
该方法返回解析后的命令行参数值,使用如下面所示:(opts, args) = parser.parse_args()
用户可以通过opts.[dest指定的变量名] 来获得解析后的参数。
相关文章推荐
- Python命令行参数解析模块optparse使用实例
- Python命令行参数解析模块getopt使用实例
- Python之命令解析模块optparse
- python optparse命令解析模块
- Python解析命令行参数模块getopt
- python optparse命令解析模块
- 转载---Python模块学习optparse 处理命令行参数
- Python 有两个内建的模块(getopt,optparse)用于处理命令行参数
- python命令行参数解析模块argparse和docopt
- python命令行参数解析模块argparse和docopt
- 深入理解python 命令行解析模块optparse(optparse源代码解读)
- python命令行参数解析模块argparse和docopt
- python命令行参数处理模块 optparse 使用参考
- Python模块:optparse 处理命令行参数
- python模块之argparse:强大的命令行参数解析模块
- Python模块学习——optparse
- Python的命令行参数解析
- 使用python的xlrd模块解析excel的多级结构
- 【python】optparse 模块
- python-Json模块【解析Json】