简体   繁体   中英

how to pass mutually exclusive argument as a variable

I was learning to handle command line arguments in Python with argparse. While not mutually exclusive arguments can be passed as variables, it is not clear to me how to do the same for mutually exclusive arguments. In the following example, I'd like to print out all the arguments. First 2 is easy. However the third one is tricky, because '-a' and '-b' have different names of destination. Therefore the last 2 lines cannot exist in the code at the same time.

#/usr/bin/env python

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-t' dest='thread', help='gtdownload thread', default=4, type=int)
parser.add_argument('-n' dest='number', help='number of downloads', default=1, type=int)

group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-a', dest='analysis', help='analysis ID')
group.add_argument('-b', dest='barcode', help='barcode')

args = parser.parser_args()

print args.thread
print args.number

#???? how to print out mutually exclusive argument
print args.analysis
print args.barcode

Most of the tutorials about add_mutually_exlusive_group out there stop at parser.parser_args() and never say what to do with the mutually exclusive arguments afterwards. But it is very important to know how exactly can the mutually exclusive arguments be passed to the rest of the code.

if args.analysis is not None:
    print args.analysis

if args.barcode is not None:
    print args.barcode

By putting -a and -b in the group, all you are telling the parser is to raise an error if you use both options in the command line.

Print args , and you will see that both attributes are present in the Namespace. The group just ensures that one will have its default value ( None ). The other will have the value you gave in the command line. Otherwise those attributes are just like the other ones.

print args  # a very useful statement when debugging argparse

(The group also affects the usage display).

You'd have to use default=argparse.SUPPRESS to keep an attribute out of the Namespace (unless given in the commandline).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM