1

I have this simple Django command I'm writing as such:

def add_arguments(self, parser):
    parser.add_argument('--type', nargs='+', type=str)
    parser.add_argument('--overwrite', nargs='?', type=bool, default=False)
    parser.add_argument('--unsubscribe', nargs='?',
                        type=bool, default=False)

def handle(self, *args, **options):

    print(options['type'])

If I run myCommand --type=all I see my type printed as ['all']. Why is this coming back as an array? I just want the string value all.

1 Answer 1

4

Its because your nargs, where you tell it to give you a list.

Read more here https://docs.python.org/3/library/argparse.html#nargs

where we can see that

'+'. Just like '*', all command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn’t at least one command-line argument present.

So you probably want '?' which parses a single value.

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.