Message198336
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 |
|
Date |
User |
Action |
Args |
2013-09-23 20:26:05 | paul.j3 | set | recipients:
+ paul.j3, bethard, eric.araujo, Paolo.Elvati, manveru, Stefan.Pfeiffer, David.Layton |
2013-09-23 20:26:05 | paul.j3 | set | messageid: <1379967965.01.0.793803450656.issue13824@psf.upfronthosting.co.za> |
2013-09-23 20:26:04 | paul.j3 | link | issue13824 messages |
2013-09-23 20:26:04 | paul.j3 | create | |
|