当然-您只需要指定一个适当的函数作为即可
type。
import argparseimport os.pathparser = argparse.ArgumentParser()def file_choices(choices,fname): ext = os.path.splitext(fname)[1][1:] if ext not in choices: parser.error("file doesn't end with one of {}".format(choices)) return fnameparser.add_argument('fn',type=lambda s:file_choices(("csv","tab"),s))parser.parse_args()演示:
temp $ python test.py test.csvtemp $ python test.py test.foousage: test.py [-h] fntest.py: error: file doesn't end with one of ('csv', 'tab')这是一种可能更干净/更通用的方法:
import argparseimport os.pathdef CheckExt(choices): class Act(argparse.Action): def __call__(self,parser,namespace,fname,option_string=None): ext = os.path.splitext(fname)[1][1:] if ext not in choices: option_string = '({})'.format(option_string) if option_string else '' parser.error("file doesn't end with one of {}{}".format(choices,option_string)) else: setattr(namespace,self.dest,fname) return Actparser = argparse.ArgumentParser()parser.add_argument('fn',action=CheckExt({'csv','txt'}))print parser.parse_args()缺点是代码在某些方面变得更加复杂-结果是,当您实际格式化参数时,接口变得更好了。



