您的位置:首页 > 运维架构

【Python 命令行参数解析: optparse 模块】

2017-08-29 19:31 633 查看
大家在使用Python进行脚本开发时,经常需要通过终端交互的方式对Python的脚本模块进行调用。这时在

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