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]

Houman
  • 64,245
  • 87
  • 278
  • 460
  • did you try just `list` - without the quotes ? From the [documentation](https://docs.python.org/3/library/argparse.html#type), 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. – karthikr Nov 03 '14 at 14:23
  • yeah I tried without the quotes and its the same problem. – Houman Nov 03 '14 at 14:37

2 Answers2

10

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
Yossi
  • 11,778
  • 2
  • 53
  • 66
  • sorry, thats an interesting idea, but it throws an exception: `optparse.OptionError: option --vpds: invalid option type: 'list'` – Houman Nov 03 '14 at 14:35
  • Removing `type='list'` fixes it. Updated the answer. – Yossi Nov 03 '14 at 14:57
  • Can anyone point me out to better info on the `action` values? I'm looking [here](https://docs.djangoproject.com/en/2.2/howto/custom-management-commands/#accepting-optional-arguments) without finding much info on what the available do or what values I can use – domdambrogia Jul 07 '19 at 00:05
  • 2
    @domdambrogia the docs actually say to check https://docs.python.org/3/library/argparse.html#action docs – Eugene K Jul 30 '19 at 10:58
0

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
Laurent Lyaudet
  • 630
  • 8
  • 16