python之argparse模块

最近工作上经常会用到argparse,这里做个简单的总结

argparse 其实就是 命令行参数解析 模块

使用方法很简单,如下所示:

1
2
3
4
5
6
7
8
import argparse

parser = argparse.ArgumentParser(description="xxxxx") #初始化
parser.add_argument("--input", required=True, help="input path") #添加参数

argments = parser.parse_args() #解析参数

print("input path {path}".format(path=argments.input)) #使用参数

关于ArgumentParser的声明如下(源码):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class ArgumentParser(_AttributeHolder, _ActionsContainer):
"""Object for parsing command line strings into Python objects.

Keyword Arguments:
- prog -- The name of the program (default: sys.argv[0])
- usage -- A usage message (default: auto-generated from arguments)
- description -- A description of what the program does
- epilog -- Text following the argument descriptions
- parents -- Parsers whose arguments should be copied into this one
- formatter_class -- HelpFormatter class for printing help messages
- prefix_chars -- Characters that prefix optional arguments
- fromfile_prefix_chars -- Characters that prefix files containing
additional arguments
- argument_default -- The default value for all arguments
- conflict_handler -- String indicating how to handle conflicts
- add_help -- Add a -h/-help option
- allow_abbrev -- Allow long options to be abbreviated unambiguously
"""

def __init__(self,
prog=None,
usage=None,
description=None,
epilog=None,
parents=[],
formatter_class=HelpFormatter,
prefix_chars='-',
fromfile_prefix_chars=None,
argument_default=None,
conflict_handler='error',
add_help=True,
allow_abbrev=True):

使用这个模块,能让参数使用的更加明确,能让其他人知道应该怎么使用参数

添加参数的时候,做好说明