使用argparse传递给python脚本的文件类型检查参数

时间:2012-10-19 15:33:08

标签: python file-type argparse

有没有办法使用argparse文件类型检查文件名参数?似乎可以通过type或choices关键字来完成,如果我可以创建正确类型的容器对象。

我希望传入一种类型的文件(例如file.txt),并希望argparse在文件类型不正确时.txt提供自动消息(usage: PROG --foo filename etc... error: argument filename must be of type *.txt. ) 。例如,argparse可能会输出

{{1}}

也许不是检测错误的文件类型,我们可以尝试检测文件名字符串不以“.txt”结尾,但这需要复杂的容器对象。

3 个答案:

答案 0 :(得分:4)

您可以使用type=关键字指定自己的类型转换器;如果您的文件名不正确,请抛出ArgumentTypeError

import argparse

def textfile(value):
    if not value.endswith('.txt'):
        raise argparse.ArgumentTypeError(
            'argument filename must be of type *.txt')
    return value

类型转换器没有来转换值..

parser.add_argument('filename', ..., type=textfile)

答案 1 :(得分:2)

不确定。您可以创建自定义操作:

class FileChecker(argparse.Action):
    def __init__(self,parser,namespace,filename,option_string=None):
        #code here to check the file, e.g...
        check_ok = filename.endswith('.txt')
        if not check_ok:
           parser.error("useful message here")
        else:
           setattr(namespace,self.dest,filename)

然后将其用作action

parser.add_argument('foo',action=FileChecker)

答案 2 :(得分:1)

我通常使用'type'参数来进行此类检查

import argparse

def foo_type(path):
    if not path.endswith(".txt"):
        raise argparse.ArgumentTypeError("Only .txt files allowed")
    return path

parser = argparse.ArgumentParser()
parser.add_argument('--foo', help='foo help', type=foo_type)
args = parser.parse_args()

示例:

$ python argp.py --foo not_my_type
usage: argp.py [-h] [--foo FOO]
argp.py: error: argument --foo: Only .txt files allowed