1.介绍
argparse是python用于解析命令行参数和选项的标准模块,用于代替已经过时的optparse模块。argparse模块的作用是用于解析命令行参数。
2.使用步骤
- 首先导入模块 import argparse
- 创建一个解析对象 parser=argparse.ArgumentParser()
- 向对象中添加命令行参数和选项 parser.add_argument()
- 最后进行解析 parser.parse_args()
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
|
| Method resolution order:
| ArgumentParser
| _AttributeHolder
| _ActionsContainer
| builtins.object
|
| Methods defined here:
|
| __init__(self, prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=<class 'argparse.HelpFormatter'>, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True)
| Initialize self. See help(type(self)) for accurate signature.
|
| add_subparsers(self, **kwargs)
| # ==================================
| # Optional/Positional adding methods
| # ==================================
|
| convert_arg_line_to_args(self, arg_line)
|
| error(self, message)
| error(message: string)
|
| Prints a usage message incorporating the message to stderr and
| exits.
|
| If you override this in a subclass, it should not return -- it
| should either exit or raise an exception.
|
| exit(self, status=0, message=None)
| # ===============
| # Exiting methods
| # ===============
|
| format_help(self)
|
| format_usage(self)
| # =======================
| # Help-formatting methods
| # =======================
|
| parse_args(self, args=None, namespace=None)
| # =====================================
| # Command line argument parsing methods
| # =====================================
|
| parse_known_args(self, args=None, namespace=None)
|
| print_help(self, file=None)
|
| print_usage(self, file=None)
| # =====================
| # Help-printing methods
| # =====================
|
| ----------------------------------------------------------------------
| Methods inherited from _AttributeHolder:
|
| __repr__(self)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _AttributeHolder:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Methods inherited from _ActionsContainer:
|
| add_argument(self, *args, **kwargs)
| add_argument(dest, ..., name=value, ...)
| add_argument(option_string, option_string, ..., name=value, ...)
|
| add_argument_group(self, *args, **kwargs)
|
| add_mutually_exclusive_group(self, **kwargs)
|
| get_default(self, dest)
|
| register(self, registry_name, value, object)
| # ====================
| # Registration methods
| # ====================
|
| set_defaults(self, **kwargs)
| # ==================================
| # Namespace default accessor methods
| # ==================================
3. 实例
#-*- coding: UTF-8 -*-
import argparse #步骤一
def test():
"""
:return:进行参数的解析
"""
description = "you should add those parameter" # 步骤二
parser = argparse.ArgumentParser(description=description) # 这些参数都有默认值,当调用parser.print_help()或者运行程序时由于参数不正确(此时python解释器其实也是调用了pring_help()方法)时,
# 会打印这些描述信息,一般只需要传递description参数,如上。
help = "your name"
parser.add_argument('--name',dest='name',help = help,required=True) # 步骤三,后面的help是我的描述
args = parser.parse_args() # 步骤四
return 'hello %s'%args.name
if __name__ == '__main__':
res = test()
print(res)