当前位置: 首页 > 工具软件 > Docopt > 使用案例 >

python参数解析模块_Python:argparse、docopt 命令行参数解析模块

秦鹏飞
2023-12-01

一、argparse

import argparse

parser = argparse.ArgumentParser()

parser.parse_args()

自带--help 参数,未定义的参数会有相应的提示

$ python3 test.py

$ python3 test.py --help

usage: test.py [-h]

optional arguments:

-h, --help show this help message and exit

$ python3 test.py --arg1

usage: test.py [-h]

test.py: error: unrecognized arguments: --arg1

想添加参数可以这么写

import argparse

parser = argparse.ArgumentParser()

parser.add_argument("arg1")

args = parser.parse_args()

print(args.arg1) #必须跟定义的参数一致

还有其他的添加方法:

parser.add_argument("--arg1","-a") 定义长参数和短参数。

带短横线和不带短横线的参数区别(个人理解)

带短横线的参数数值紧跟在后,不带的本身内容就是参数值。

带短横线的参数是可选参数,不带的是必须参数

parser.add_argument("arg1",help="help content") 自带帮助内容

parser.add_argument("arg1",help="help content",type=int) 定义参数的类型

parser.add_argument("arg1",help="help content",type=int,default=100) 定义参数的默认值

parser.add_argument('--show','-s',help='content',action="store_true", default=False) 定义布尔值类型参数

最后一个可以简单的理解为如果命令行参数有--show,则 args.show 为真,没有则为假

最后取出参数数值都是用args.[argument_name]得到,记得最初定义的类型。

二、docopt

这是最近才知道的一个用法。docopt可以用写文档的方式完成参数定义,真正是doc + opt 啊。

"""Naval Fate.

Usage:

naval_fate.py ship new ...

naval_fate.py ship move [--speed=]

naval_fate.py ship shoot

naval_fate.py mine (set|remove) [--moored|--drifting]

naval_fate.py -h | --help

naval_fate.py --version

Options:

-h --help Show this screen.

--version Show version.

--speed= Speed in knots [default: 10].

--moored Moored (anchored) mine.

--drifting Drifting mine.

"""

from docopt import docopt

if __name__ == '__main__':

arguments = docopt(__doc__, version='Naval Fate 2.0')

print(arguments)

__doc__ 的内容根据需要从Usage Arguments Options Examples 里选择(区分大小写)。

大写或者由尖括号括起来的是参数

带一个或者两个短横线是选项,-a -b -c 可以写成 -abc

方括号里的是必选元素,圆括号里的是可选元素,|分隔开互斥元素(多个里选一个),...代表一个或者多个元素。

这一部分里的选项另起一行,以短横线开始。

用两个空格分隔开选项和描述。

想添加默认值,则在描述结束后添加 [default: ]

默认值是否会被拆分,请看下面的例子。

Usage: my_program.py [--repeatable= --repeatable=]

[--another-repeatable=]...

[--not-repeatable=]

# will be ['./here', './there']

--repeatable= [default: ./here ./there]

# will be ['./here']

--another-repeatable= [default: ./here]

# will be './here ./there', because it is not repeatable

--not-repeatable= [default: ./here ./there]

Arguments

解释参数内容

Examples

直接填写样例

如果用样例,输入naval_fate.py ship Guardian move 100 150 --speed=15

结果将会是

{'--drifting': False, 'mine': False,

'--help': False, 'move': True,

'--moored': False, 'new': False,

'--speed': '15', 'remove': False,

'--version': False, 'set': False,

'': ['Guardian'], 'ship': True,

'': '100', 'shoot': False,

'': '150'}

 类似资料: