1

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

4
  • 3
    There's a 'append' `action value. Check the docs. Commented Nov 30, 2021 at 6:41
  • Thanks @hpaulj append works but I am seeing it like test=[['train1'], ['train2']]) is this expected behavior. Commented Nov 30, 2021 at 6:50
  • 2
    What's your nargs? 'append' makes a list, nargs can add another layer. Commented Nov 30, 2021 at 7:14
  • 1
    I see ya, I was using nargs='+' which was causing this behavior. Removing this helped me solve the issue. This was great help. Commented Nov 30, 2021 at 7:39

1 Answer 1

1

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 '])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.