如何停止argparse.FileType创建指定为默认的文件

Joh*_*ill 8 python argparse

我喜欢这个argparse模块.argparse.FileType也是有帮助的,除非您希望默认值不是sys.std*因为即使您提供值也会创建默认输出文件.

例如:

parser.add_argument('--outfile', type=FileType('w'), default="out.txt")
Run Code Online (Sandbox Code Playgroud)

即使您使用--outfile指定文件,也会创建out.txt.

我能想到的最好的是:

class MagicFileType(object):

    def __init__(self, *args, **kwargs):

        # save args/kwargs and set filetype to None
        self.filetype = None
        self.args = args
        self.kwargs = kwargs

    def __getattr__(self, attr):
        """ Delegate everything to the filetype """

        # If we haven't created it, now is the time to do so
        if self.filetype is None:
            self.filetype = FileType(*self.args, **self.kwargs)
            self.filetype = self.filetype(self.filename)

        return getattr(self.filetype, attr)

    def __call__(self, filename):
        """ Just cache the filename """

        # This is called when the default is created
        # Just cache the filename for now.
        self.filename = filename
        return self
Run Code Online (Sandbox Code Playgroud)

但如果觉得这样比较容易,我会错过什么吗?

hpa*_*ulj 3

http://bugs.python.org/issue12776(2012argparse年 8 月)中有一个相对较新的更改,延迟了默认值的评估。最初,字符串默认值将在解析开始时通过(via )传递,从而导致打开(和创建)FileType 文件(无论是否需要)。在此补丁中,字符串被写入命名空间,但直到解析结束才进行评估,此时可以确定是否提供了另一个值。基本上,这条线从早期移到了末尾type_get_valueparse_known_args_parse_known_args

default = self._get_value(action, action.default)
Run Code Online (Sandbox Code Playgroud)

在http://bugs.python.org/issue13824中,我提出了一个提供FileContext类型的补丁。它的主要区别在于FileType它将包装open(file...)在partial. 这样,文件在实际在with args.output() as f:上下文中使用之前不会打开(或创建)。

该补丁处理其他一些事情,例如测试文件是否可以创建(使用os.access)以及包装stdin/out在虚拟上下文中,以便它不会尝试关闭它。

无需测试,您可以FileType这样修改:

class FileOpener(argparse.FileType):
    # delayed FileType;
    # sample use:
    # with args.input.open() as f: f.read()
    def __call__(self, string):
        # optionally test string
        self.filename = string
        return self
    def open(self):
        return super(FileOpener,self).__call__(self.filename)
    file =  property(open, None, None, 'open file property')
Run Code Online (Sandbox Code Playgroud)