argparse
能否用于验证文件名命令行参数的文件扩展名?
例如如果我有一个 python 脚本,我从 cmd 行运行:
$ script.py file.csv
$ script.py file.tab
$ script.py file.txt
我希望 argparse 接受第一个两个文件名 cmd 行选项但拒绝第三个
我知道你可以这样做:
parser = argparse.ArgumentParser()
parser.add_argument("fn", choices=["csv","tab"])
args = parser.parse_args()
为命令行选项指定两个有效选项
我想要的是:
parser.add_argument("fn", choices=["*.csv","*.tab"])
为 cmd 行选项指定两个有效的文件扩展名。不幸的是,这行不通 - 有没有办法使用 argparse
来实现这一点?
最佳答案
当然——您只需要指定一个适当的函数作为类型
。
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')
这里有一个可能更简洁/通用的方法:
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()
这里的缺点是代码在某些方面变得有点复杂 -- 结果是当你真正去格式化你的参数时,界面变得更清晰了。
关于python argparse文件扩展名检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15203829/