1. argparse介绍
Python内置的sys.argv保存了完整的参数列表,我们可以从中解析出需要的参数。
但这种方式解析稍微复杂点的参数就非常麻烦,比如可以使用-d复制目录,使用--filename *.py过滤文件名等。
argparse 模块就可以解决这些问题。
示例1:
# test.py
import argparse
def main():
# 定义一个ArgumentParser实例:
parser = argparse.ArgumentParser(
prog='backup', # 程序名
description='Backup MySQL database.', # 描述
epilog='Copyright(r), 2023' # 说明信息
)
# 定义位置参数:
parser.add_argument('outfile')
# 定义关键字参数:
parser.add_argument('--host', default='localhost')
# 此参数必须为int类型:
parser.add_argument('--port', default='3306', type=int)
# 允许用户输入简写的-u:
parser.add_argument('-u', '--user', required=True)
parser.add_argument('-p', '--password', required=True)
parser.add_argument('--database', required=True)
# gz参数不跟参数值,因此指定action='store_true',意思是出现-gz表示True:
parser.add_argument('-gz', '--gzcompress', action='store_true', required=False, help='Compress backup files by gz.')
# 解析参数:
args = parser.parse_args()
# 打印参数:
print('parsed args:')
print(f'outfile = {args.outfile}')
print(f'host = {args.host}')
print(f'port = {args.port}')
print(f'user = {args.user}')
print(f'password = {args.password}')
print(f'database = {args.database}')
print(f'gzcompress = {args.gzcompress}')
if __name__ == '__main__':
main()
$ ./test.py -u root -p hello --database testdb backup.sql
parsed args:
outfile = backup.sql
host = localhost
port = 3306
user = root
password = hello
database = testdb
gzcompress = False
示例2:
# argparse_positional.py
# 位置参数不传,会报错
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('name', help='your full name')
args = parser.parse_args()
print(args.name)
$ python argparse_positional.py
usage: argparse_positional.py [-h] name
argparse_positional.py: error: too few arguments
$ python argparse_positional.py -h
usage: argparse_positional.py [-h] name
positional arguments:
name your full name
optional arguments:
$ python argparse_positional.py Foo
Foo
示例3:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--color', '-c', help='The name of the color')
parser.add_argument('--verbose', '-v', help='Print more data',
action='store_true')
args = parser.parse_args()
print(args.color)
print(args.verbose)
$ python argparse_shortname.py -c Blue -v
$ python argparse_shortname.py -vc Blue
Blue
True
2. add_argument参数
命令行参数的解析主要是靠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 - 命令行遇到参数时的动作,默认值是 store。
- store, 默认值, 存储参数的值。
- store_const,存储由 const 关键字参数指定的值,请注意 const 关键字参数默认为
None。parser.add_argument('--foo', action='store_const', const=42)。 - store_true 和store_false 是 store_const分别用作存储 True 和 False 值的特殊用例,
parser.add_argument('--foo', action='store_true') - append,存储一个列表,并将每个参数值添加到该列表。
parser.add_argument('--foo', action='append'),使用python test.py --foo 1 --foo 2 - type, 命令行参数应当被转换成的类型。
- const, 被一些 action 和 nargs 选择所需求的常数。
- default, 当参数未在命令行中出现并且也不存在于命名空间对象时所产生的值。
- count,计算一个关键字参数出现的数目或次数。
- nargs - 应该读取的命令行参数个数,可以是
- 数字
N,命令行中的 N 个参数会被聚集到一个列表中 ?号,如果可能的话,会从命令行中消耗一个参数,并产生一个单独项。 如果当前没有命令行参数,将会使用 default 值。*号,表示 0 或多个参数;+号表示 1 或多个参数。
- 数字
- const - action 和 nargs 所需要的常量值。
- default - 不指定参数时的默认值。
- type - 命令行参数应该被转换成的类型。
- choices - 参数可允许的值的一个容器。
- required - 可选参数是否可以省略 (仅针对可选参数)。
- help - 参数的帮助信息,当指定为 argparse.SUPPRESS 时表示不显示该参数的帮助信息.
- metavar - 在 usage 说明中的参数名称,对于必选参数默认就是参数名称,对于可选参数默认是全大写的参数名称.
- dest - 解析后的参数名称,默认情况下,对于可选参数选取最长的名称,中划线转换为下划线.
1166

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



