60

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.

totokaka
  • 2,244
  • 1
  • 21
  • 33

1 Answers1

90

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

totokaka
  • 2,244
  • 1
  • 21
  • 33
  • Excellent. It even supports `*` and `+` too, with the results that might be expected from knowledge regular expressions. – Thomas Ahle Feb 01 '17 at 13:12
  • @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. – jmon12 Oct 04 '22 at 08:13