1. 我们能用 argparse 干什么?
argparse模块可以通过命令行的方式获取用户输入的信息,还可以向用户提供帮助信息,当用户输入无效参数时报错。
argparse是通过sys.argv来解析出参数的,两者也可以联合使用。
2. argparse 最最基本的使用模板
import argparse
# 第一步,创建ArgumentParse对象
parse = argparse.ArgumentParser(description='Process some integers')
# ArgumentParse对象通过parse_args函数来解析参数,实际上是从sys.argv中确定命令行参数
args = parse.parse_args()
在创建ArgumentParser对象时,除了description,还有其他参数可以添加:
class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True)
创建一个新的 ArgumentParser 对象。所有的参数都应当作为关键字参数传入。每个参数在下面都有它更详细的描述,但简而言之,它们是:
-
prog - 程序的名称(默认:
sys.argv[0]) -
usage - 描述程序用途的字符串(默认值:从添加到解析器的参数生成)
-
description - 在参数帮助文档之前显示的文本(默认值:无)
-
epilog - 在参数帮助文档之后显示的文本(默认值:无)
-
parents - 一个
ArgumentParser对象的列表,它们的参数也应包含在内 -
formatter_class - 用于自定义帮助文档输出格式的类
-
prefix_chars - 可选参数的前缀字符集合(默认值:'-')
-
fromfile_prefix_chars - 当需要从文件中读取其他参数时,用于标识文件名的前缀字符集合(默认值:
None) -
argument_default - 参数的全局默认值(默认值:
None) -
conflict_handler - 解决冲突选项的策略(通常是不必要的)
-
add_help - 为解析器添加一个
-h/--help选项(默认值:True) -
allow_abbrev - 如果缩写是无歧义的,则允许缩写长选项 (默认值:
True)
import argparse
# prog参数用于指定文件名,默认是从sys.argv[0]读取的
parse = argparse.ArgumentParser(prog='wow', description='Process some integers')
parse.add_argument('--foo', help='foo of the %(prog)s program') # 可以通过 %(prog)s来引用
parse.print_help()
输出:
usage: wow [-h] [--foo FOO]
Process some integers
optional arguments:
-h, --help show this help message and exit
--foo FOO foo of the wow program
3. 要求用户输入一些信息
import argparse
parse = argparse.ArgumentParser(prog='wow', description='Process some integers')
parse.add_argument('square', type=int, help='calculate square of the given number') # 位置参数,必须添加
parse.add_argument('-f','--foo', help='foo of the %(prog)s program') # 一个参数选项
args = parse.parse_args()
add_argument() 方法
ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
定义单个的命令行参数应当如何解析。每个形参都在下面有它自己更多的描述,长话短说有:
-
name or flags - 一个命名或者一个选项字符串的列表,例如
foo或-f, --foo。 -
action - 当参数在命令行中出现时使用的动作基本类型。
-
nargs - 命令行参数应当消耗的数目。
-
default - 当参数未在命令行中出现时使用的值。
-
type - 命令行参数应当被转换成的类型。
-
choices - 可用的参数的容器。
-
required - 此命令行选项是否可省略 (仅选项可用)。
-
help - 一个此选项作用的简单描述。
-
metavar - 在使用方法消息中使用的参数值示例。
-
dest - 被添加到
parse_args()所返回对象上的属性名。
说说常用的几个参数:
1)action (指定命令行参数应该如何处理)
action可选的动作有:
-'store' : 默认动作,存储参数的值
-'store_const': 存储const参数指定的值,特殊的使用方法是store_true, store_false
import argparse
parse = argparse.ArgumentParser(description='Process some integers')
parse.add_argument('--foo', action='store_const', const=42)
args = parse.parse_args()
print(args)
输出:
(venv) D:\code_test>python test1.py --foo
Namespace(foo=42)
import argparse
parse = argparse.ArgumentParser(description='Process some integers')
parse.add_argument('--foo', action='store_true')
args = parse.parse_args()
print(args)
输出:
(venv) D:\code_test>python test1.py --foo
Namespace(foo=True)
-'append :将参数值追加到一个列表中,需要多次调用对应的参数
import argparse
parse = argparse.ArgumentParser(description='Process some integers')
parse.add_argument('--foo', action='append')
args = parse.parse_args()
print(args)
输出:
(venv) D:\code_test>python test1.py --foo 1 --foo 2
Namespace(foo=['1', '2'])
本文介绍了Python的argparse模块,用于通过命令行获取用户输入信息,并提供帮助和错误处理。主要内容包括ArgumentParser的基本使用、参数解析模板、add_argument方法以及常用action选项的解释。

3120

被折叠的 条评论
为什么被折叠?



