__init__() 在 Python 2 中使用 argparse 得到了一个意外的关键字参数"必需"



我有下面的python脚本,如果我用Python 2.7.16版本运行,那么我会得到一个错误,但如果用Python 3版本运行,它会正常工作。

以下是我的代码:

from argparse import ArgumentParser
def parse_cli_arguments():
parser = ArgumentParser(
description='some stuff'
)
parser.add_argument(
"-v",
"--verbose",
help="verbose output",
action="store_true"
)
subparser = parser.add_subparsers(
title="action",
dest='action',
required=True,
help='action sub-command help'
)
# create the subparser for the "push" command
parser_push = subparser.add_parser(
'push',
help='push help'
)
parser_push.add_argument(
'environment',
type=str,
help='push environment help'
)
parser_push.add_argument(
'instance',
type=str,
help='push instance help'
)
parser_push.add_argument(
'config',
type=str,
help='push config help'
)
# create the subparser for the "status" command
parser_status = subparser.add_parser(
'status',
help='status help'
)
parser_status.add_argument(
'environment',
type=str,
help='status environment help'
)
parser_status.add_argument(
'instance',
type=str,
help='status instance help'
)
return parser
def main():
parser = parse_cli_arguments()
args = parser.parse_args()
if args.action == 'push':
print('You chose push:', args.environment, args.instance, args.config)
elif args.action == 'status':
print('You chose status:', args.environment, args.instance)
else:
print('Something unexpected happened')

if __name__ == '__main__':
main()

问题陈述

以下是我在使用Python 2.7.16版本时遇到的错误。有没有想过我在这里做错了什么?

我需要在Python 2.7.16版本上运行上面的代码。

❯ python test.py
Traceback (most recent call last):
File "test.py", line 70, in <module>
main()
File "test.py", line 59, in main
parser = parse_cli_arguments()
File "test.py", line 17, in parse_cli_arguments
help='action sub-command help'
File "/Users/andy/.pyenv/versions/2.7.16/lib/python2.7/argparse.py", line 1678, in add_subparsers
action = parsers_class(option_strings=[], **kwargs)
TypeError: __init__() got an unexpected keyword argument 'required'

我需要在这里更改一些语法以使其与Python2一起工作吗?

2.7和3之间的api发生了变化。sub_parsers以前没有required关键字arg。

这是2.7中的函数签名。文档

ArgumentParser.add_subparsers([title][, description][, prog][, parser_class][, action][, option_string][, dest][, help][, metavar])

它在3.9文档中

ArgumentParser.add_subparsers([title][, description][, prog][, parser_class][, action][, option_string][, dest][, required][, help][, metavar])

@hpaulj提出了一种解决方法,包括在add_subparsers调用后设置所需的属性。你可以在这里找到答案(并留下任何赞成票(。

相关内容

最新更新