0

I would like to allow a user to enter in multiple ids as an argument. For example, something like:

import argparse

parser = argparse.ArgumentParser(description='Dedupe assets based on group_id.')
parser.add_argument('--ids', nargs='?', default=None, type=int, help='Enter your ids')
parser.parse_args()

Yet when I enter in something like:

$ python test.py --ids 1 2 3 4

I get the following error:

test.py: error: unrecognized arguments: 2 3 4

What would be the proper way to allow/enter in multiple arguments for a single option?

David542
  • 104,438
  • 178
  • 489
  • 842
  • 1
    Does this answer your question? [How can I pass a list as a command-line argument with argparse?](https://stackoverflow.com/questions/15753701/how-can-i-pass-a-list-as-a-command-line-argument-with-argparse) – Maurice Meyer Sep 09 '20 at 20:49
  • @MauriceMeyer Oh, I see. nargs is lazy so I need to do `+` instead of `?`. – David542 Sep 09 '20 at 20:54
  • 1
    '?' is `optional' (0 or 1), '+' is 1 or more, etc. It tries to follow `regex` conventions where it makes sense. Look at 'nargs/?' in the docs for more details. – hpaulj Sep 09 '20 at 21:53
  • @hpaulj oh I was mixing up `?` and `*` (0 or more). Is `*` supported by nargs ? – David542 Sep 10 '20 at 03:31

1 Answers1

0

you can use '+' rather than '?'.

import argparse

parser = argparse.ArgumentParser(description='Dedupe assets based on group_id.')
parser.add_argument('--ids', nargs='+', default=None, type=int, help='Enter your ids')
args = parser.parse_args()

print(args.ids)