Search code examples
pythonargparse

Multiple argument in python argparse


I want my script to take multiple argument with same name.

python3 script.py --test test1 --test test2 --test test3 --config config_path

How can I achieve this. I have tried nargs from argparse till now.

# My Solution
import argparse

parser = argparse.ArgumentParser(description='Arg Parser',
            formatter_class=argparse.ArgumentDefaultsHelpFormatter,
            allow_abbrev=False)

parser.add_argument('--test', nargs='+', required=True, \
                help='Modules name for sanity check', choices=['test1 ', 'test2 ', 'test3 '])

parser.add_argument('--config')

arg = parser.parse_args()

But it's behavior is little different it takes it in the form

python3 script.py --test test1 test2 --config config_path

Any suggestion on how to get desired behavior


Solution

  • This should be straight forward from @hpaulj comments adding code just in case

    parser.add_argument('--test', action='append', required=True, \
                    choices=['test1 ', 'test2 ', 'test3 '])