Mutually exclusive options with argparse.

hongy...@gmail.com hongyi.zhao at gmail.com
Wed Sep 1 08:09:21 EDT 2021


See the following code snippets [1] for implementation of the exclusive options with argparse:

def query_builder(args):
    if args.r and args.s:
        sys.exit(Term.FAIL + 'Only one of -re and -sql should be set' + Term.ENDC)
    sum_status = sum(1 for x in [args.failure, args.code != -1] if x)
    if sum_status > 1:
        sys.exit(Term.FAIL + ('Only one of --failure and --code has to be set') + Term.ENDC)

[1] https://github.com/hongyi-zhao/recent2/blob/5486afbd56a6b06bb149a3ea969fb33d9d8b288f/recent2.py#L391

It seems that the above method is awkward, but I'm out of idea to work out more graceful solutions. Any comment/suggestion/enhancement will be highly appreciated.

Regards,
HY


More information about the Python-list mailing list