python argparse文件扩展名检查 [英] python argparse file extension checking
问题描述
可以使用 argparse
来验证文件名 cmd 行参数的文件扩展名吗?
can argparse
be used to validate filename extensions for a filename cmd line parameter?
例如如果我有一个从 cmd 行运行的 python 脚本:
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
我知道你可以这样做:
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 行选项指定两个有效的文件扩展名.不幸的是,这不起作用 - 有没有办法使用 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屋!