我正在使用Python 3.4,正在尝试argparse
与子解析器一起使用,并且我希望具有与Python 2.x中类似的行为,如果我不提供位置参数(以指示子解析器/子程序)我会收到一条有用的错误消息。即,随着python2
我将得到以下错误消息:
$ python2 subparser_test.py
usage: subparser_test.py [-h] {foo} ...
subparser_test.py: error: too few arguments
我正在required
按照https://stackoverflow.com/a/22994500/3061818中的建议设置属性,但是这给我Python 3.4.0带来了错误: TypeError: sequence item 0: expected str instance, NoneType found
-完全回溯:
$ python3 subparser_test.py
Traceback (most recent call last):
File "subparser_test.py", line 17, in <module>
args = parser.parse_args()
File "/usr/local/Cellar/python3/3.4.0/Frameworks/Python.framework/Versions/3.4/lib/python3.4/argparse.py", line 1717, in parse_args
args, argv = self.parse_known_args(args, namespace)
File "/usr/local/Cellar/python3/3.4.0/Frameworks/Python.framework/Versions/3.4/lib/python3.4/argparse.py", line 1749, in parse_known_args
namespace, args = self._parse_known_args(args, namespace)
File "/usr/local/Cellar/python3/3.4.0/Frameworks/Python.framework/Versions/3.4/lib/python3.4/argparse.py", line 1984, in _parse_known_args
', '.join(required_actions))
TypeError: sequence item 0: expected str instance, NoneType found
这是我的程序subparser_test.py
-改编自https://docs.python.org/3.2/library/argparse.html#sub-commands:
import argparse
# sub-command functions
def foo(args):
print('"foo()" called')
# create the top-level parser
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
subparsers.required = True
# create the parser for the "foo" command
parser_foo = subparsers.add_parser('foo')
parser_foo.set_defaults(func=foo)
args = parser.parse_args()
args.func(args)