0

I'm using argparse to make a command line tool for my work.
I have a requirement wherein an argument should be able to take multiple values.

The argument can take only legal values.

The legal values can be any combination of values coming from a list, "ALL".

sample.py:

import argparse

sample_list = ["a", "b", "c"]

parser = argparse.ArgumentParser()

parser.add_argument('-M', '--Module', choices=sample_list, default=default_module, help='specify the Module name')
args = parser.parse_args()

Using the above approach the allowed values the allowed values are:

python sample.py -M a

I want that user is able to enter:

python sample.py -M a,b
<ok>

python sample.py -M ALL
<ok>

python sample.py -M D
<error>

How to achieve this?

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Amit Goel
  • 35
  • 1
  • 10

1 Answers1

0

The simplest solution would be to include ALL is the list of allowable choices, and use either action='append' or nargs='*' to accept multiple values. I'd leave the interpretation of ALL to post-parsing code.

As has been discussed in other SO questions, trying to handle comma delimited sublists is a pain.

hpaulj
  • 221,503
  • 14
  • 230
  • 353