| 1 | """ |
| 2 | The temp module defines a NamedTemporaryFile |
| 3 | that can be re-opened. |
| 4 | |
| 5 | This is needed because in Windows NT, the |
| 6 | default implementation of NamedTemporaryFile |
| 7 | uses the O_TEMPORARY flag, and thus cannot |
| 8 | be reopened [1]. |
| 9 | |
| 10 | 1: http://mail.python.org/pipermail/python-list/2005-December/359474.html |
| 11 | """ |
| 12 | |
| 13 | import os |
| 14 | import tempfile |
| 15 | |
| 16 | __all__ = ('NamedTemporaryFile', 'gettempdir',) |
| 17 | |
| 18 | class TemporaryFile(object): |
| 19 | """ |
| 20 | Temporary file object constructor that works |
| 21 | in Windows and supports reopening of the |
| 22 | temporary file in windows. |
| 23 | """ |
| 24 | def __init__(self, mode='w+b', bufsize=-1, suffix='', prefix='', 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 | |
| 30 | def __del__(self): |
| 31 | try: |
| 32 | self._file.close() |
| 33 | except (OSError, IOError): |
| 34 | pass |
| 35 | try: |
| 36 | os.unlink(self.name) |
| 37 | except (OSError): |
| 38 | pass |
| 39 | |
| 40 | super(TemporaryFile, self).__del__() |
| 41 | |
| 42 | |
| 43 | def read(self, *args): return self._file.read(*args) |
| 44 | def seek(self, offset): return self._file.seek(offset) |
| 45 | def write(self, s): return self._file.write(s) |
| 46 | def close(self): return self._file.close() |
| 47 | def __iter__(self): return iter(self._file) |
| 48 | def readlines(self, size=None): return self._file.readlines(size) |
| 49 | def xreadlines(self): return self._file.xreadlines() |
| 50 | |
| 51 | |
| 52 | if os.name == 'nt': |
| 53 | NamedTemporaryFile = TemporaryFile |
| 54 | else: |
| 55 | NamedTemporaryFile = tempfile.NamedTemporaryFile |
| 56 | |
| 57 | gettempdir = tempfile.gettempdir |