A temporary file object which allows shared reading. All the temporary files created by the `tempfile` module's functions are accessible by the calling process only on some operating systems. Therefore this class represents a file which is deleted as soon as the object is destroyed
| 39 | |
| 40 | |
| 41 | class TempFile(object): |
| 42 | """A temporary file object which allows shared reading. |
| 43 | |
| 44 | All the temporary files created by the `tempfile` module's functions are |
| 45 | accessible by the calling process only on some operating systems. |
| 46 | Therefore this class represents a file which is deleted as soon as the |
| 47 | object is destroyed but without keeping the file open all the time. |
| 48 | """ |
| 49 | |
| 50 | def __init__(self, mode='r'): |
| 51 | """Initialize TempFile object.""" |
| 52 | self.name = tempfile.mktemp(dir=TEMP_DIR) |
| 53 | self._file = None |
| 54 | self._mode = mode |
| 55 | # Cache unlink to keep it available even though the 'os' module is |
| 56 | # already None'd out whenever __del__() is called. |
| 57 | # See python stdlib's tempfile.py for details. |
| 58 | self._unlink = os.unlink |
| 59 | |
| 60 | try: |
| 61 | # ensure cache directory exists with write permissions |
| 62 | os.makedirs(TEMP_DIR, 0o700) |
| 63 | except OSError as e: |
| 64 | if e.errno != errno.EEXIST: |
| 65 | raise |
| 66 | |
| 67 | def __del__(self): |
| 68 | """Destroy the TempFile object and remove the file from disk.""" |
| 69 | try: |
| 70 | self.close() |
| 71 | self._unlink(self.name) |
| 72 | except OSError: |
| 73 | pass |
| 74 | |
| 75 | def __enter__(self): |
| 76 | """`With` statement support.""" |
| 77 | return self.open() |
| 78 | |
| 79 | def __exit__(self, exc, value, tb): |
| 80 | """`With` statement support.""" |
| 81 | self.close() |
| 82 | |
| 83 | def open(self): |
| 84 | """Open temporary file.""" |
| 85 | if self._file is None: |
| 86 | self._file = open(self.name, mode=self._mode) |
| 87 | return self._file |
| 88 | |
| 89 | def close(self): |
| 90 | """Close temporary file.""" |
| 91 | if self._file is not None: |
| 92 | self._file.close() |
| 93 | self._file = None |
| 94 | |
| 95 | def tell(self): |
| 96 | return self._file.tell() |