|
1 """ |
|
2 The temp module provides a NamedTemporaryFile that can be re-opened on any |
|
3 platform. Most platforms use the standard Python tempfile.TemporaryFile class, |
|
4 but MS Windows users are given a custom class. |
|
5 |
|
6 This is needed because in Windows NT, the default implementation of |
|
7 NamedTemporaryFile uses the O_TEMPORARY flag, and thus cannot be reopened [1]. |
|
8 |
|
9 1: http://mail.python.org/pipermail/python-list/2005-December/359474.html |
|
10 """ |
|
11 |
|
12 import os |
|
13 import tempfile |
|
14 |
|
15 __all__ = ('NamedTemporaryFile', 'gettempdir',) |
|
16 |
|
17 if os.name == 'nt': |
|
18 class TemporaryFile(object): |
|
19 """ |
|
20 Temporary file object constructor that works in Windows and supports |
|
21 reopening of the temporary file in windows. |
|
22 """ |
|
23 def __init__(self, mode='w+b', bufsize=-1, suffix='', prefix='', |
|
24 dir=None): |
|
25 fd, name = tempfile.mkstemp(suffix=suffix, prefix=prefix, |
|
26 dir=dir) |
|
27 self.name = name |
|
28 self.file = os.fdopen(fd, mode, bufsize) |
|
29 self.close_called = False |
|
30 |
|
31 # Because close can be called during shutdown |
|
32 # we need to cache os.unlink and access it |
|
33 # as self.unlink only |
|
34 unlink = os.unlink |
|
35 |
|
36 def close(self): |
|
37 if not self.close_called: |
|
38 self.close_called = True |
|
39 try: |
|
40 self.file.close() |
|
41 except (OSError, IOError): |
|
42 pass |
|
43 try: |
|
44 self.unlink(self.name) |
|
45 except (OSError): |
|
46 pass |
|
47 |
|
48 def __del__(self): |
|
49 self.close() |
|
50 |
|
51 def read(self, *args): return self.file.read(*args) |
|
52 def seek(self, offset): return self.file.seek(offset) |
|
53 def write(self, s): return self.file.write(s) |
|
54 def __iter__(self): return iter(self.file) |
|
55 def readlines(self, size=None): return self.file.readlines(size) |
|
56 def xreadlines(self): return self.file.xreadlines() |
|
57 |
|
58 NamedTemporaryFile = TemporaryFile |
|
59 else: |
|
60 NamedTemporaryFile = tempfile.NamedTemporaryFile |
|
61 |
|
62 gettempdir = tempfile.gettempdir |