python argparse文件扩展名检查 [英] python argparse file extension checking
问题描述
argparse
可以用于验证文件名cmd行参数的文件名扩展名吗?
can argparse
be used to validate filename extensions for a filename cmd line parameter?
例如如果我有python脚本,则从cmd行运行:
e.g. if i have a python script i run from the cmd line:
$ script.py file.csv
$ script.py file.tab
$ script.py file.txt
我希望argparse接受第一个两个文件名cmd行选项,但拒绝第三个
i would like argparse to accept the 1st two filename cmd line options but reject the 3rd
我知道您可以执行以下操作:
i know you can do something like this:
parser = argparse.ArgumentParser()
parser.add_argument("fn", choices=["csv","tab"])
args = parser.parse_args()
为cmd行选项指定两个有效选择
to specify two valid choices for a cmd line option
我想要的是什么
parser.add_argument("fn", choices=["*.csv","*.tab"])
为cmd line选项指定两个有效的文件扩展名.不幸的是,这行不通-是否可以使用argparse
来实现这一目标?
to specify two valid file extensions for the cmd line option. Unfortunately this doesn't work - is there a way to achieve this using argparse
?
推荐答案
当然-您只需要指定一个适当的函数作为type
.
Sure -- you just need to specify an appropriate function as the type
.
import argparse
import os.path
parser = 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 fname
parser.add_argument('fn',type=lambda s:file_choices(("csv","tab"),s))
parser.parse_args()
演示:
temp $ python test.py test.csv
temp $ python test.py test.foo
usage: test.py [-h] fn
test.py: error: file doesn't end with one of ('csv', 'tab')
这是一种可能更干净/更通用的方法:
Here's a possibly more clean/general way to do it:
import argparse
import os.path
def 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 Act
parser = argparse.ArgumentParser()
parser.add_argument('fn',action=CheckExt({'csv','txt'}))
print parser.parse_args()
这里的缺点是代码在某些方面变得更加复杂-结果是,当您实际格式化参数时,接口变得更整洁了.
The downside here is that the code is getting a bit more complicated in some ways -- The upshot is that the interface gets a good bit cleaner when you actually go to format your arguments.
这篇关于python argparse文件扩展名检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!