I was just looking at custom management commands (Django 3.2) and noted that the error handling for a subparser didn't match the Django behaviour without some extra, undocumented work.
If my Command subclass implements the following:
def add_arguments(self, parser):
subparsers = parser.add_subparsers()
sub = subparsers.add_parser("thing")
errors raised by the subparser, eg, for missing arguments, result in the command exiting with a stack trace. Normal behaviour in Django when a command is called from the command line is a nice error message and I expect subparsers to act the same way.
The error handling behaviour depends on the parser.called_from_command_line attribute which must be set manually for subparsers to achieve the same, eg:
sub = subparsers.add_parser("thing",
called_from_command_line=parser.called_from_command_line)
I'd propose adding a little documentation about this argument
with an example so that the next me doesn't need to hunt through the code to understand what's happening.
Another option would be to add a convenience method
that would ensure
called_from_command_line
is set correctly, eg,
class CommandParser:
def add_subparser(self, subparsers, name, **kwargs):
kwargs.setdefault(
"called_from_command_line",
self.called_from_command_line
)
return subparsers.add_parser(name, **kwargs)
which would save repetition but would still require command authors have some special Django knowledge so I'd question whether it's worthwhile.
I'm happy to contribute if advised on the preferred option.
Cheers
Mark