Re: argsparse: allowing --version without mandatory options

"Loris Bennett" <[email protected]>
Newsgroups gmane.comp.python.general
Organization FUB-IT, Freie Universität Berlin
Message-ID <[email protected]>
"Loris Bennett" <[email protected]> writes:

> Hi,
>
> I am writing a program for the command-line which uses 'argsparse'.  I
> want to make some options mandatory by setting 'required=True', but
> still allow the program to run with the option '--version' (which just
> shows the version and then exits) even if the mandatory options are
> missing.
>
> Is there a standard way of doing this?

I see that instead of setting required to 'True' I can use an expression
which checks whether '--version' has been given:

    parser.add_argument(
        "uid", nargs="+",
        help="UIDs to send mail to"
    )
    parser.add_argument(
        '-s', '--subject', dest='subject', required=not '--version' in sys.argv,
        help="subject of email"
    )
    parser.add_argument(
        '-c', '--content_file', dest='content_file', required=not '--version' in sys.argv,
        help="file containing mail contents (without salutation or signature)"
    )
    parser.add_argument(
        '--version', action='store_true', dest='version',
        help="print version"

However, with the above, I still need to specify the mandatory argument,
even if I only want to see the version.

I guess I'll just have to change 

  nargs="+" 

to 

  nargs="*"

and check explicitly whether any arguments have been given.

Seems odd to me though that there is not a standard way of implementing
'--version' which works like '--help' does.

Cheers,

Loris

-- 
This signature is currently under constuction.
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.