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

Matt Wheeler m at funkyhat.org
Sun Nov 27 19:18:24 EST 2022


I wondered whether subparsers might work, but they don't quite fit here.

This seems to fit the bill fairly well, though I agree it would be
nice if there were a neater option:

import argparse
import sys

VERSION = 0.1

def main(args):
    parser.parse_args(args)


class VersionAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string):
        print(VERSION)
        exit()


parser = argparse.ArgumentParser()
parser.add_argument("-v", "--version", nargs=0, action=VersionAction)
parser.add_argument("pos", nargs=1)


if __name__ == "__main__":
    main(sys.argv[1:])

On Sun, 27 Nov 2022 at 23:40, Skip Montanaro <skip.montanaro at gmail.com> wrote:
>
> I have a script to which I'd like to add a --version flag. It should print
> the version number then exit, much in the same way --help prints the help
> text then exits. I haven't been able to figure that out. I always get a
> complaint about the required positional argument.
>
> I think I could use something like nargs='*', but that would push off
> detection of the presence of the positional arg to the application.
> Shouldn't I be able to tell argparse I'm going to process --verbose, then
> exit?
>
> Thx,
>
> Skip
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Matt Wheeler
http://funkyh.at


More information about the Python-list mailing list