Re: argparse — adding a --version flag in the face of positional args

Skip Montanaro skip.montanaro at gmail.com
Sun Nov 27 19:24:31 EST 2022


> class VersionAction(argparse.Action):
>     def __call__(self, parser, namespace, values, option_string):
>         print(VERSION)
>         exit()
...
> parser.add_argument("-v", "--version", nargs=0, action=VersionAction)

Thanks. An action class didn't occur to me. I looked briefly at the
code for argparse to see how it handled --help. The added argument
seemed normal, so gave up, figuring there was some special handling of
that option.

Skip


More information about the Python-list mailing list