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

Chris Angelico rosuav at gmail.com
Mon Nov 28 21:14:44 EST 2022


On Tue, 29 Nov 2022 at 12:37, Loris Bennett <loris.bennett at fu-berlin.de> wrote:
>
> Mats Wichmann <mats at wichmann.us> writes:
>
> > On 11/27/22 16:40, Skip Montanaro 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?
> >
> > ummm, hate to say this, but have you checked the documentation?  this
> > case is supported using an action named 'version' without doing very
> > much.
>
> I hadn't noticed the action 'version'.  I just use
>
>     parser.add_argument(
>         "-v", "--version", action="store_true", dest="version",
>         help="print version"
>     )
>

That's still going to validate the rest of the args though - notably,
you can't omit any mandatory arguments (like a subcommand).

The version and help actions are implemented pretty simply, actually.
They're just little action classes that do their action immediately on
getting triggered. It should be easy enough to make any action you
want that way.

ChrisA


More information about the Python-list mailing list