MCPcopy
hub / github.com/django/django / CommandParser

Class CommandParser

django/core/management/base.py:49–89  ·  view source on GitHub ↗

Customized ArgumentParser class to improve some error messages and prevent SystemExit in several occasions, as SystemExit is unacceptable when a command is called programmatically.

Source from the content-addressed store, hash-verified

47
48
49class CommandParser(ArgumentParser):
50 """
51 Customized ArgumentParser class to improve some error messages and prevent
52 SystemExit in several occasions, as SystemExit is unacceptable when a
53 command is called programmatically.
54 """
55
56 def __init__(
57 self, *, missing_args_message=None, called_from_command_line=None, **kwargs
58 ):
59 self.missing_args_message = missing_args_message
60 self.called_from_command_line = called_from_command_line
61 if PY314:
62 if not PY315:
63 kwargs.setdefault("suggest_on_error", True)
64 if os.environ.get("DJANGO_COLORS") == "nocolor" or "--no-color" in sys.argv:
65 kwargs.setdefault("color", False)
66 super().__init__(**kwargs)
67
68 def parse_args(self, args=None, namespace=None):
69 # Catch missing argument for a better error message
70 if self.missing_args_message and not (
71 args or any(not arg.startswith("-") for arg in args)
72 ):
73 self.error(self.missing_args_message)
74 return super().parse_args(args, namespace)
75
76 def error(self, message):
77 if self.called_from_command_line:
78 super().error(message)
79 else:
80 raise CommandError("Error: %s" % message)
81
82 def add_subparsers(self, **kwargs):
83 parser_class = kwargs.get("parser_class", type(self))
84 if issubclass(parser_class, CommandParser):
85 kwargs["parser_class"] = partial(
86 parser_class,
87 called_from_command_line=self.called_from_command_line,
88 )
89 return super().add_subparsers(**kwargs)
90
91
92def handle_default_options(options):

Callers 3

executeMethod · 0.90
get_command_line_optionFunction · 0.85
create_parserMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected