Argparse mit erforderlichem Subparser

Ich benutze Python 3.4, ich versuche es zu benutzenargparse mit Subparsern, und ich möchte ein ähnliches Verhalten wie in Python 2.x haben. Wenn ich kein Positionsargument gebe (um den Subparser / das Subprogramm anzugeben), erhalte ich eine hilfreiche Fehlermeldung. Das heißt, mitpython2 Ich erhalte folgende Fehlermeldung:

$ python2 subparser_test.py    
usage: subparser_test.py [-h] {foo} ...
subparser_test.py: error: too few arguments

Ich stelle das einrequired Attribut wie in vorgeschlagenhttps://stackoverflow.com/a/22994500/3061818Das gibt mir jedoch einen Fehler mit Python 3.4.0:TypeError: sequence item 0: expected str instance, NoneType found - vollständiger Traceback:

$ 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

Das ist mein Programmsubparser_test.py - angepasst vonhttps://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)

Verwandte Frage:Warum verhält sich dieser Argparse-Code zwischen Python 2 und 3 anders?

Antworten auf die Frage(1)

Ihre Antwort auf die Frage