Subparsers for management commands

136 views
Skip to first unread message

Mark Gregson

unread,
Jan 10, 2023, 9:31:38 PM1/10/23
to Django developers (Contributions to Django itself)
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

Adam Johnson

unread,
Jan 15, 2023, 4:23:56 AM1/15/23
to django-d...@googlegroups.com
Hi Mark

I agree that subparsers should use the same error formatting.

After looking at the problem a bit more, I found a solution to pass called_from_command_line through to subparsers by changing CommandParser. I filed a ticket and a PR: https://code.djangoproject.com/ticket/34259#ticket

Thanks,

Adam

--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-developers/06855745-cff7-4474-8538-2589d0a0a650n%40googlegroups.com.

Mark Gregson

unread,
Jan 15, 2023, 6:50:56 PM1/15/23
to Django developers (Contributions to Django itself)

Thanks Adam, nice solution.
Reply all
Reply to author
Forward
0 new messages