Mercurial > hg > config
comparison python/fileobj.py @ 498:95ba5770d2f0
file decorator
author | Jeff Hammel <jhammel@mozilla.com> |
---|---|
date | Wed, 21 Aug 2013 15:54:09 -0700 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
497:2e51a55d303d | 498:95ba5770d2f0 |
---|---|
1 #!/usr/bin/env python | |
2 | |
3 """ | |
4 filename -> file-like object as a decorator | |
5 """ | |
6 | |
7 import optparse | |
8 import os | |
9 import sys | |
10 | |
11 string = (basestring,) | |
12 | |
13 class fileobj(object): | |
14 def __init__(self, arg, *args, **kwargs): | |
15 self._args = [arg] + list(args) | |
16 self._kwargs = kwargs | |
17 # mode, filename, ... | |
18 | |
19 # function | |
20 self.func = arg if not args else None | |
21 def __call__(self, *args, **kwargs): | |
22 if self.func is None: | |
23 raise NotImplementedError | |
24 else: | |
25 if len(args) and isinstance(args[0], string): | |
26 args = list(args) | |
27 with file(args[0], 'w') as fp: | |
28 args[0] =fp | |
29 return self.func(*args, **kwargs) | |
30 return self.func(*args, **kwargs) | |
31 | |
32 if __name__ == '__main__': | |
33 # test code | |
34 import os | |
35 import tempfile | |
36 | |
37 @fileobj | |
38 def test1(fp): | |
39 fp.write('foo') | |
40 | |
41 filename = tempfile.mktemp() | |
42 print filename | |
43 assert not os.path.exists(filename) | |
44 test1(filename) | |
45 assert os.path.exists(filename) | |
46 print file(filename).read() |