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

Skip Montanaro skip.montanaro at gmail.com
Mon Nov 28 11:36:17 EST 2022


Thanks. It occurs to me that instead of providing two special actions
("help" and "version"), it might be worthwhile to provide a standard way of
saying, "if present, process this option and exit before considering other
details of the command line." Matt's example action works well enough for
my needs, but it would be nice if more than one such option could be given.
For example:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("url")
parser.add_argument("--version", version="777", action="version")

args = parser.parse_args(["--help", "--version"])

Which option is processed depends on their order on the command line. I
don't believe it's possible to run the script and see them both processed.
That's probably a secondary consideration though. My script is working well
enough in this regard now.

Skip


More information about the Python-list mailing list