Here is an excerpt from some code that I use for a similar purpose:
def parse_args(argv): class SetAction(argparse.Action): """argparse.Action subclass to store distinct values""" def __call__(self, parser, namespace, values, option_string=None): try: getattr(namespace,self.dest).update( values ) except AttributeError: setattr(namespace,self.dest,set(values)) ap = argparse.ArgumentParser( description = __doc__, formatter_class = argparse.ArgumentDefaultsHelpFormatter, ) ap.add_argument('--genes', '-g', type = lambda v: v.split(','), action = SetAction, help = 'select by specified gene')
This is similar in spirit to the jcollado answer with a slight improvement: you can specify several options with values โโseparated by commas, and they are released (via a set) in all respects.
For instance:
snafu$ ./bin/ucsc-bed -g BRCA1,BRCA2,DMD,TNFA,BRCA2 -g BRCA1 Namespace(genes=set([u'BRCA1', u'BRCA2', u'DMD', u'TNFA']))
Note that there are two -g arguments. BRCA2 is indicated twice in the first, but appears only once. BRCA1 is indicated in the first and second variants of -g, but also appears only once.
source share