标签:ini 默认值 float amp 方式 ret 说明文 帮助信息 code
大家在使用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()" 是最为重要的方法
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 | 用于提醒用户参数应输入的值 | 显示为大写 | 
说明
该方法返回解析后的命令行参数值,使用如下面所示:
(opts, args) = parser.parse_args()
用户可以通过opts.[dest指定的变量名] 来获得解析后的参数。
更多内容请关注卫星公众号

标签:ini 默认值 float amp 方式 ret 说明文 帮助信息 code
原文地址:https://www.cnblogs.com/nelson2013/p/9251949.html