Call the given command, with the given options and args/kwargs. This is the primary API you should use for calling specific commands. `command_name` may be a string or a command object. Using a string is preferred unless the command object is required for further processing or
(command_name, *args, **options)
| 81 | |
| 82 | |
| 83 | def call_command(command_name, *args, **options): |
| 84 | """ |
| 85 | Call the given command, with the given options and args/kwargs. |
| 86 | |
| 87 | This is the primary API you should use for calling specific commands. |
| 88 | |
| 89 | `command_name` may be a string or a command object. Using a string is |
| 90 | preferred unless the command object is required for further processing or |
| 91 | testing. |
| 92 | |
| 93 | Some examples: |
| 94 | call_command('migrate') |
| 95 | call_command('shell', plain=True) |
| 96 | call_command('sqlmigrate', 'myapp') |
| 97 | |
| 98 | from django.core.management.commands import flush |
| 99 | cmd = flush.Command() |
| 100 | call_command(cmd, verbosity=0, interactive=False) |
| 101 | # Do something with cmd ... |
| 102 | """ |
| 103 | if isinstance(command_name, BaseCommand): |
| 104 | # Command object passed in. |
| 105 | command = command_name |
| 106 | command_name = command.__class__.__module__.split(".")[-1] |
| 107 | else: |
| 108 | # Load the command object by name. |
| 109 | try: |
| 110 | app_name = get_commands()[command_name] |
| 111 | except KeyError: |
| 112 | raise CommandError("Unknown command: %r" % command_name) |
| 113 | |
| 114 | if isinstance(app_name, BaseCommand): |
| 115 | # If the command is already loaded, use it directly. |
| 116 | command = app_name |
| 117 | else: |
| 118 | command = load_command_class(app_name, command_name) |
| 119 | |
| 120 | # Simulate argument parsing to get the option defaults (see #10080 for |
| 121 | # details). |
| 122 | parser = command.create_parser("", command_name) |
| 123 | # Use the `dest` option name from the parser option |
| 124 | opt_mapping = { |
| 125 | min(s_opt.option_strings).lstrip("-").replace("-", "_"): s_opt.dest |
| 126 | for s_opt in parser._actions |
| 127 | if s_opt.option_strings |
| 128 | } |
| 129 | arg_options = {opt_mapping.get(key, key): value for key, value in options.items()} |
| 130 | parse_args = [] |
| 131 | for arg in args: |
| 132 | if isinstance(arg, (list, tuple)): |
| 133 | parse_args += map(str, arg) |
| 134 | else: |
| 135 | parse_args.append(str(arg)) |
| 136 | |
| 137 | def get_actions(parser): |
| 138 | # Parser actions and actions from sub-parser choices. |
| 139 | for opt in parser._actions: |
| 140 | if isinstance(opt, _SubParsersAction): |