python argparse文件扩展名检查

标签 python argparse

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/

相关文章:

python - 如何在单次遍历中找到python链表中的中间元素?

python - 无法摆脱 BeautifulSoup 造成的导航问题

python - 向 argparse 参数添加附加参数

Python argparse 可选子参数

python - 找到 TypeError : coercing to Unicode: need string or buffer, 列表

python - IO错误 : [Errno 2] No such file or directory error is presented for the ouptup file

python 当 id 相同时做某事

python - 尝试让 python RegEx 删除括号 [ abc ] 之间的所有内容

python - 如何从 python 中的 HashMap 中创建直方图?

python - 使用 argparse 指定默认文件名,但不在 --help 上打开它们?