How to specify a parameter of type Array into a Django Command?
Asked Answered
P

2

7

It is straight forward creating a string parameter such as --test_email_address below.

   class Command(BaseCommand):
        option_list = BaseCommand.option_list + (
            make_option('--test_email_address',
                        action='store',
                        type="string",
                        dest='test_email_address',
                        help="Specifies test email address."),
            make_option('--vpds',
                        action='store',
                        type='list',           /// ??? Throws exception
                        dest='vpds',
                        help="vpds list [,]"),
        )

But how can I define a list to be passed in? such as [1, 3, 5]

Pulpwood answered 3/11, 2014 at 14:12 Comment(2)
did you try just list - without the quotes ? From the documentation, it looks like type can be any valid simple types. The other (hacky) way is to read the arguments as string, and parse it using ast.literal_eval or something.Cursive
yeah I tried without the quotes and its the same problem.Pulpwood
P
11

You should add a default value and change the action to 'append':

make_option('--vpds',
            action='append',
            default=[],
            dest='vpds',
            help="vpds list [,]"),

The usage is as follows:

python manage.py my_command --vpds arg1 --vpds arg2
Perlaperle answered 3/11, 2014 at 14:24 Comment(4)
sorry, thats an interesting idea, but it throws an exception: optparse.OptionError: option --vpds: invalid option type: 'list'Pulpwood
Removing type='list' fixes it. Updated the answer.Perlaperle
Can anyone point me out to better info on the action values? I'm looking here without finding much info on what the available do or what values I can useParterre
@Parterre the docs actually say to check docs.python.org/3/library/argparse.html#action docsRipplet
S
2

You can also do it like this:

        parser.add_argument(
            "--vpds",
            nargs="*",
            help="vpds list",
            default=[],
            type=int,
        )

The usage is as follows:

python manage.py my_command --vpds 1 3 5
Specs answered 30/5, 2023 at 14:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.