python 命令行参数解析、并设置默认值_【Python 命令行参数解析: optparse 模块】...

大家在使用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指定的变量名] 来获得解析后的参数。

更多内容请关注卫星公众号

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值