62

I am creating a python script where I want to have an argument that manipulates how many search results you get as output. I've currently named the argument --head. This is the functionality I'd like it to have:

  1. When --head is not passed at the command line I'd like it to default to one value. In this case, a rather big one, like 80

  2. When --head is passed without any value, I'd like it to default to another value. In this case, something limited, like 10

  3. When --head is passed with a value, I'd like it to store the value it was passed.

Here is some code describing the problem:

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-h',
                        '--head',
                        dest='size',
                        const=80,
                        default=10,
                        action="I don't know",
                        help='Only print the head of the output')
>>> # OFC, that last line will fail because the action is uknown,
... # but here is how I'd like it to work
... parser.parse_args(''.split())
Namespace(size=80)
>>> parser.parse_args('--head'.split())
Namespace(size=10)
>>> parser.parse_args('--head 15'.split())
Namespace(size=15)

I know I probably can write a custom action for this, but I first want to see if there is any default behaviour that does this.

1 Answer 1

96

After a little more reading in the documentation I found what I needed: nargs='?'. This is used with the store action, and does exactly what I want.

Here is an example:

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--head',
                        dest='size',
                        const=10,
                        default=80,
                        action='store',
                        nargs='?',
                        type=int,
                        help='Only print the head of the output')
>>> parser.parse_args(''.split())
... Namespace(size=80)
>>> parser.parse_args('--head'.split())
... Namespace(size=10)
>>> parser.parse_args('--head 15'.split())
... Namespace(size=15)

Source: http://docs.python.org/3/library/argparse.html#nargs

Sign up to request clarification or add additional context in comments.

2 Comments

Excellent. It even supports * and + too, with the results that might be expected from knowledge regular expressions.
@ThomasAhle const argument cannot be used with *. The way to go in that case seems to be [] if the option is provided without argument(s), and None if it hasn't been provided.

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.