paul j3 added the comment:

In this patch I implement a FileContext class.  It differs from FileType
in 2 key areas:

- it returns a 'partial(open, filename, ...)'
- it wraps '-' (stdin/out) in a dummy context protecting the file from closure.

The resulting argument is meant to be used as:

    with args.input() as f:
        f.read()
        etc

The file is not opened until value is called, and it will be closed after the 
block.  stdin/out can also be used in this context, but without closing.

The signature for this class is the same as for FileType, with one added 
parameter, 'style'. (alternative name suggestions welcomed).

class argparse.FileContext(mode='r', bufsize=-1, encoding=None, errors=None, 
style='delayed')

The default behavior, "style='delayed'", is as described above.

"style='evaluate'" immediately calls the partial, returning an opened file.  
This is essentially the same as FileType, except for the stdin/out context 
wrapping.

"style='osaccess'", adds os.acccess testing to determine whether the 'delayed' 
file can be read or written.  It attempts to catch the same sort of OS errors 
that  FileType would, but without actually opening or creating the file.

Most of the added tests in test_argparse.py copy the FileType tests.  I had to 
make some modifications to the testing framework to handle the
added levels of indirection.

I have not written the documentation changes yet.

A sample use case is:

    import argparse, sys
    p = argparse.ArgumentParser()
    p.add_argument('-d','--delayed', type=argparse.FileContext('r'))
    p.add_argument('-e','--evaluated', type=argparse.FileContext('r', 
style='evaluate'))
    p.add_argument('-t','--test', dest='delayed', 
type=argparse.FileContext('r', style='osaccess'))
    p.add_argument('-o','--output', type=argparse.FileContext('w', 
style='osaccess'), default='-')
    p.add_argument('--unused', type=argparse.FileContext('w', 
style='osaccess'),help='unused write file')
    args = p.parse_args()

    with args.output() as o:
        if args.delayed:
            with args.delayed() as f:
                print(f.read(), file=o)
        if args.evaluated:
            with args.evaluated as f:
                print(f.read(), file=o)
    # f and o will be closed if regular files
    # but not if stdin/out
    # the file referenced by args.unused will not be created

----------
keywords: +patch
Added file: http://bugs.python.org/file31852/patch_3.diff

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue13824>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to