5

I've a management command with the following argument parser section:

class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument('--out', action='store', dest='out', required=True)
        parser.add_argument('--todos', action='store', dest='todos', \
                required=True, nargs='+')
        parser.add_argument('--filter', action='store', dest='filter')
        parser.add_argument('--list', action='store', dest='list')
        parser.add_argument('--add_id', action='store_true', dest='add_id')

. I'm trying to call this command from a view / shell, but does not work:

from django.core.management import call_command
call_command('prg_name', out='/tmp/111.txt')

, however i got the following error: argument --out is required .

The program is kinda old: python: 2.7 Django: 1.11.16

.

How should i call the call_command with parameters with this old layout?

What is strange, if i do this:

dt = {'--out=/tmp/111.txt': sth}
call_command(prg_name, *dt)

it works, however i can't define more value for --todos .

3
  • What is sth here? Commented Mar 7, 2020 at 21:29
  • Some random value. Just to make work the dictionary. Commented Mar 7, 2020 at 21:30
  • but here you perform sequence unpacking (there is only one asterisk *, not multiple ones), hence it will only look at the keys of the dictionaries, but you can pass a tuple, list, any iterable anyway. Commented Mar 7, 2020 at 21:31

1 Answer 1

7

You can just pass an arbitrary number of strings to the command:

call_command(prg_name, '--out=/tmp/111.txt', '--todos', '8', '12', '105', '51')

You can see these as the parameters that you would have passed to your program if you called it from the command line.

Sign up to request clarification or add additional context in comments.

10 Comments

Well, it solves the problem of --out, but for the --todos it takes only the latest one..
@user2194805: are you sure that is not because of the handling in your command itself. I would find it strange that the call_command itself is the problem since this basically just passes these, and are parsed by the argument parser: github.com/django/django/blob/master/django/core/management/…
@user2194805: what if you run the command from the command line?
It works fine from the command line: python manage.py create_document --out /tmp/444 --todos 8 12 105 51 {'add_id': False, 'settings': None, 'pythonpath': None, 'verbosity': 1, 'traceback': False, 'list': None, 'filter': None, 'no_color': False, 'todos': ['8', '12', '105', '51'], 'out': '/tmp/444'}
@user2194805: ah, but then you need to pass it like that as well.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.