How to make an optional value for argument using argparse?

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)