3

I have written a python script which uses argeparse module for handling arguments. e.g.

Test_Dual.py -g Linux

Now, I want to give it two options for same argument, like

Test_Dual.py -g Linux -g ESX -g Windows

How can I do that?

Marcin
  • 215,873
  • 14
  • 235
  • 294
akkidukes
  • 189
  • 1
  • 1
  • 9

2 Answers2

3

You can do as follows:

import argparse

parser = argparse.ArgumentParser(description=("Program desciption"))


parser.add_argument("-g", "--full-name-of-g", action='append',
                    help="what is g option for")

args = vars(parser.parse_args())

print(args['full_name_of_g'])

Prints:

['Linux', 'ESX', 'Windows']
Marcin
  • 215,873
  • 14
  • 235
  • 294
2

You want the 'append' action to add_argument. This will accumulate values into a list -- once for each time the command line argument is present. e.g.

parser = argparse.ArgumentParser()  # yadda yadda
parser.add_argument('-g', action='append')

fake_args_for_demo = '-g Linux -g ESX -g Windows'.split()
namespace = parser.parse_args(fake_args_for_demo)

print(namespace.g)  # ['Linux', 'ESX', 'Windows']
mgilson
  • 300,191
  • 65
  • 633
  • 696