栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

python argparse文件扩展名检查

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python argparse文件扩展名检查

当然-您只需要指定一个适当的函数作为即可

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()

缺点是代码在某些方面变得更加复杂-结果是,当您实际格式化参数时,接口变得更好了。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/659958.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号