Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 1 | """Temporary files. |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 2 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 3 | This module provides generic, low- and high-level interfaces for |
| 4 | creating temporary files and directories. The interfaces listed |
| 5 | as "safe" just below can be used without fear of race conditions. |
| 6 | Those listed as "unsafe" cannot, and are provided for backward |
| 7 | compatibility only. |
Guido van Rossum | eee9498 | 1991-11-12 15:38:08 +0000 | [diff] [blame] | 8 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 9 | This module also provides some data items to the user: |
Guido van Rossum | eee9498 | 1991-11-12 15:38:08 +0000 | [diff] [blame] | 10 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 11 | TMP_MAX - maximum number of names that will be tried before |
| 12 | giving up. |
| 13 | template - the default prefix for all temporary names. |
| 14 | You may change this to control the default prefix. |
| 15 | tempdir - If this is set to a string before the first use of |
| 16 | any routine from this module, it will be considered as |
| 17 | another candidate location to store temporary files. |
| 18 | """ |
Skip Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 19 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 20 | __all__ = [ |
| 21 | "NamedTemporaryFile", "TemporaryFile", # high level safe interfaces |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 22 | "SpooledTemporaryFile", "TemporaryDirectory", |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 23 | "mkstemp", "mkdtemp", # low level safe interfaces |
| 24 | "mktemp", # deprecated unsafe interface |
| 25 | "TMP_MAX", "gettempprefix", # constants |
| 26 | "tempdir", "gettempdir" |
| 27 | ] |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 28 | |
Tim Peters | 4fd5a06 | 2002-01-28 23:11:23 +0000 | [diff] [blame] | 29 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 30 | # Imports. |
Tim Peters | 4fd5a06 | 2002-01-28 23:11:23 +0000 | [diff] [blame] | 31 | |
Nick Coghlan | 6b22f3f | 2010-12-12 15:24:21 +0000 | [diff] [blame] | 32 | import warnings as _warnings |
| 33 | import sys as _sys |
Guido van Rossum | 9a63470 | 2007-07-09 10:24:45 +0000 | [diff] [blame] | 34 | import io as _io |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 35 | import os as _os |
| 36 | import errno as _errno |
| 37 | from random import Random as _Random |
| 38 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 39 | try: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 40 | import fcntl as _fcntl |
Tim Peters | 90ee7eb | 2004-07-18 23:58:17 +0000 | [diff] [blame] | 41 | except ImportError: |
Tim Peters | 291f14e | 2003-07-22 02:50:01 +0000 | [diff] [blame] | 42 | def _set_cloexec(fd): |
| 43 | pass |
| 44 | else: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 45 | def _set_cloexec(fd): |
Tim Peters | 90ee7eb | 2004-07-18 23:58:17 +0000 | [diff] [blame] | 46 | try: |
| 47 | flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0) |
| 48 | except IOError: |
| 49 | pass |
Alex Martelli | f09994e | 2003-11-09 16:44:09 +0000 | [diff] [blame] | 50 | else: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 51 | # flags read successfully, modify |
| 52 | flags |= _fcntl.FD_CLOEXEC |
| 53 | _fcntl.fcntl(fd, _fcntl.F_SETFD, flags) |
Tim Peters | 291f14e | 2003-07-22 02:50:01 +0000 | [diff] [blame] | 54 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 55 | |
| 56 | try: |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 57 | import _thread |
Guido van Rossum | a093424 | 2002-12-30 22:36:09 +0000 | [diff] [blame] | 58 | except ImportError: |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 59 | import _dummy_thread as _thread |
Guido van Rossum | a093424 | 2002-12-30 22:36:09 +0000 | [diff] [blame] | 60 | _allocate_lock = _thread.allocate_lock |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 61 | |
| 62 | _text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 63 | if hasattr(_os, 'O_NOINHERIT'): |
| 64 | _text_openflags |= _os.O_NOINHERIT |
| 65 | if hasattr(_os, 'O_NOFOLLOW'): |
| 66 | _text_openflags |= _os.O_NOFOLLOW |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 67 | |
| 68 | _bin_openflags = _text_openflags |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 69 | if hasattr(_os, 'O_BINARY'): |
| 70 | _bin_openflags |= _os.O_BINARY |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 71 | |
| 72 | if hasattr(_os, 'TMP_MAX'): |
| 73 | TMP_MAX = _os.TMP_MAX |
| 74 | else: |
| 75 | TMP_MAX = 10000 |
| 76 | |
Tim Peters | bd7b4c7 | 2002-08-13 23:33:56 +0000 | [diff] [blame] | 77 | template = "tmp" |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 78 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 79 | # Internal routines. |
| 80 | |
| 81 | _once_lock = _allocate_lock() |
| 82 | |
Guido van Rossum | b25615939 | 2003-11-10 02:16:36 +0000 | [diff] [blame] | 83 | if hasattr(_os, "lstat"): |
| 84 | _stat = _os.lstat |
| 85 | elif hasattr(_os, "stat"): |
| 86 | _stat = _os.stat |
| 87 | else: |
| 88 | # Fallback. All we need is something that raises os.error if the |
| 89 | # file doesn't exist. |
| 90 | def _stat(fn): |
| 91 | try: |
| 92 | f = open(fn) |
| 93 | except IOError: |
| 94 | raise _os.error |
| 95 | f.close() |
| 96 | |
| 97 | def _exists(fn): |
| 98 | try: |
| 99 | _stat(fn) |
| 100 | except _os.error: |
| 101 | return False |
| 102 | else: |
| 103 | return True |
| 104 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 105 | class _RandomNameSequence: |
| 106 | """An instance of _RandomNameSequence generates an endless |
| 107 | sequence of unpredictable strings which can safely be incorporated |
| 108 | into file names. Each string is six characters long. Multiple |
| 109 | threads can safely use the same instance at the same time. |
| 110 | |
| 111 | _RandomNameSequence is an iterator.""" |
| 112 | |
Raymond Hettinger | 572895b | 2010-11-09 03:43:58 +0000 | [diff] [blame] | 113 | characters = "abcdefghijklmnopqrstuvwxyz0123456789_" |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 114 | |
Antoine Pitrou | 4558bad | 2011-11-25 21:28:15 +0100 | [diff] [blame] | 115 | @property |
| 116 | def rng(self): |
| 117 | cur_pid = _os.getpid() |
| 118 | if cur_pid != getattr(self, '_rng_pid', None): |
| 119 | self._rng = _Random() |
| 120 | self._rng_pid = cur_pid |
| 121 | return self._rng |
Tim Peters | 97701b5 | 2002-11-21 15:59:59 +0000 | [diff] [blame] | 122 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 123 | def __iter__(self): |
| 124 | return self |
| 125 | |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 126 | def __next__(self): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 127 | c = self.characters |
Tim Peters | 97701b5 | 2002-11-21 15:59:59 +0000 | [diff] [blame] | 128 | choose = self.rng.choice |
Raymond Hettinger | 572895b | 2010-11-09 03:43:58 +0000 | [diff] [blame] | 129 | letters = [choose(c) for dummy in "123456"] |
| 130 | return ''.join(letters) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 131 | |
| 132 | def _candidate_tempdir_list(): |
| 133 | """Generate a list of candidate temporary directories which |
| 134 | _get_default_tempdir will try.""" |
| 135 | |
| 136 | dirlist = [] |
| 137 | |
| 138 | # First, try the environment. |
| 139 | for envname in 'TMPDIR', 'TEMP', 'TMP': |
| 140 | dirname = _os.getenv(envname) |
| 141 | if dirname: dirlist.append(dirname) |
| 142 | |
| 143 | # Failing that, try OS-specific locations. |
Alexandre Vassalotti | eca20b6 | 2008-05-16 02:54:33 +0000 | [diff] [blame] | 144 | if _os.name == 'nt': |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 145 | dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ]) |
| 146 | else: |
| 147 | dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ]) |
| 148 | |
| 149 | # As a last resort, the current directory. |
| 150 | try: |
| 151 | dirlist.append(_os.getcwd()) |
| 152 | except (AttributeError, _os.error): |
| 153 | dirlist.append(_os.curdir) |
| 154 | |
| 155 | return dirlist |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 156 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 157 | def _get_default_tempdir(): |
| 158 | """Calculate the default directory to use for temporary files. |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 159 | This routine should be called exactly once. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 160 | |
| 161 | We determine whether or not a candidate temp dir is usable by |
| 162 | trying to create and write to a file in that directory. If this |
| 163 | is successful, the test file is deleted. To prevent denial of |
| 164 | service, the name of the test file must be randomized.""" |
| 165 | |
| 166 | namer = _RandomNameSequence() |
| 167 | dirlist = _candidate_tempdir_list() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 168 | |
| 169 | for dir in dirlist: |
| 170 | if dir != _os.curdir: |
| 171 | dir = _os.path.normcase(_os.path.abspath(dir)) |
| 172 | # Try only a few names per directory. |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 173 | for seq in range(100): |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 174 | name = next(namer) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 175 | filename = _os.path.join(dir, name) |
| 176 | try: |
Amaury Forgeot d'Arc | 7d0bddd | 2009-11-30 00:08:56 +0000 | [diff] [blame] | 177 | fd = _os.open(filename, _bin_openflags, 0o600) |
Guido van Rossum | 5424df2 | 2007-08-13 19:06:38 +0000 | [diff] [blame] | 178 | fp = _io.open(fd, 'wb') |
| 179 | fp.write(b'blat') |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 180 | fp.close() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 181 | _os.unlink(filename) |
| 182 | del fp, fd |
| 183 | return dir |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 184 | except (OSError, IOError) as e: |
Georg Brandl | 7816e51 | 2007-10-22 12:42:46 +0000 | [diff] [blame] | 185 | if e.args[0] != _errno.EEXIST: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 186 | break # no point trying more names in this directory |
| 187 | pass |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 188 | raise IOError(_errno.ENOENT, |
| 189 | "No usable temporary directory found in %s" % dirlist) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 190 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 191 | _name_sequence = None |
| 192 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 193 | def _get_candidate_names(): |
| 194 | """Common setup sequence for all user-callable interfaces.""" |
| 195 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 196 | global _name_sequence |
| 197 | if _name_sequence is None: |
| 198 | _once_lock.acquire() |
| 199 | try: |
| 200 | if _name_sequence is None: |
| 201 | _name_sequence = _RandomNameSequence() |
| 202 | finally: |
| 203 | _once_lock.release() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 204 | return _name_sequence |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 205 | |
| 206 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 207 | def _mkstemp_inner(dir, pre, suf, flags): |
| 208 | """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.""" |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 209 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 210 | names = _get_candidate_names() |
| 211 | |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 212 | for seq in range(TMP_MAX): |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 213 | name = next(names) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 214 | file = _os.path.join(dir, pre + name + suf) |
| 215 | try: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 216 | fd = _os.open(file, flags, 0o600) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 217 | _set_cloexec(fd) |
Martin v. Löwis | d662548 | 2003-10-12 17:37:01 +0000 | [diff] [blame] | 218 | return (fd, _os.path.abspath(file)) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 219 | except OSError as e: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 220 | if e.errno == _errno.EEXIST: |
| 221 | continue # try again |
| 222 | raise |
| 223 | |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 224 | raise IOError(_errno.EEXIST, "No usable temporary file name found") |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 225 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 226 | |
| 227 | # User visible interfaces. |
Guido van Rossum | b0e5718 | 1998-10-14 20:27:05 +0000 | [diff] [blame] | 228 | |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 229 | def gettempprefix(): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 230 | """Accessor for tempdir.template.""" |
| 231 | return template |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 232 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 233 | tempdir = None |
| 234 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 235 | def gettempdir(): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 236 | """Accessor for tempfile.tempdir.""" |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 237 | global tempdir |
| 238 | if tempdir is None: |
| 239 | _once_lock.acquire() |
| 240 | try: |
| 241 | if tempdir is None: |
| 242 | tempdir = _get_default_tempdir() |
| 243 | finally: |
| 244 | _once_lock.release() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 245 | return tempdir |
| 246 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 247 | def mkstemp(suffix="", prefix=template, dir=None, text=False): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 248 | """User-callable function to create and return a unique temporary |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 249 | file. The return value is a pair (fd, name) where fd is the |
| 250 | file descriptor returned by os.open, and name is the filename. |
| 251 | |
| 252 | If 'suffix' is specified, the file name will end with that suffix, |
| 253 | otherwise there will be no suffix. |
| 254 | |
| 255 | If 'prefix' is specified, the file name will begin with that prefix, |
| 256 | otherwise a default prefix is used. |
| 257 | |
| 258 | If 'dir' is specified, the file will be created in that directory, |
| 259 | otherwise a default directory is used. |
| 260 | |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 261 | If 'text' is specified and true, the file is opened in text |
| 262 | mode. Else (the default) the file is opened in binary mode. On |
| 263 | some operating systems, this makes no difference. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 264 | |
| 265 | The file is readable and writable only by the creating user ID. |
| 266 | If the operating system uses permission bits to indicate whether a |
| 267 | file is executable, the file is executable by no one. The file |
| 268 | descriptor is not inherited by children of this process. |
| 269 | |
| 270 | Caller is responsible for deleting the file when done with it. |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 271 | """ |
| 272 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 273 | if dir is None: |
| 274 | dir = gettempdir() |
| 275 | |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 276 | if text: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 277 | flags = _text_openflags |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 278 | else: |
| 279 | flags = _bin_openflags |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 280 | |
| 281 | return _mkstemp_inner(dir, prefix, suffix, flags) |
Guido van Rossum | cff3454 | 1992-01-14 18:31:56 +0000 | [diff] [blame] | 282 | |
Guido van Rossum | eee9498 | 1991-11-12 15:38:08 +0000 | [diff] [blame] | 283 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 284 | def mkdtemp(suffix="", prefix=template, dir=None): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 285 | """User-callable function to create and return a unique temporary |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 286 | directory. The return value is the pathname of the directory. |
| 287 | |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 288 | Arguments are as for mkstemp, except that the 'text' argument is |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 289 | not accepted. |
| 290 | |
| 291 | The directory is readable, writable, and searchable only by the |
| 292 | creating user. |
| 293 | |
| 294 | Caller is responsible for deleting the directory when done with it. |
| 295 | """ |
| 296 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 297 | if dir is None: |
| 298 | dir = gettempdir() |
| 299 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 300 | names = _get_candidate_names() |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 301 | |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 302 | for seq in range(TMP_MAX): |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 303 | name = next(names) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 304 | file = _os.path.join(dir, prefix + name + suffix) |
| 305 | try: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 306 | _os.mkdir(file, 0o700) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 307 | return file |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 308 | except OSError as e: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 309 | if e.errno == _errno.EEXIST: |
| 310 | continue # try again |
| 311 | raise |
| 312 | |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 313 | raise IOError(_errno.EEXIST, "No usable temporary directory name found") |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 314 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 315 | def mktemp(suffix="", prefix=template, dir=None): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 316 | """User-callable function to return a unique temporary file name. The |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 317 | file is not created. |
| 318 | |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 319 | Arguments are as for mkstemp, except that the 'text' argument is |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 320 | not accepted. |
| 321 | |
| 322 | This function is unsafe and should not be used. The file name |
| 323 | refers to a file that did not exist at some point, but by the time |
| 324 | you get around to creating it, someone else may have beaten you to |
| 325 | the punch. |
| 326 | """ |
| 327 | |
Guido van Rossum | 44f602d | 2002-11-22 15:56:29 +0000 | [diff] [blame] | 328 | ## from warnings import warn as _warn |
| 329 | ## _warn("mktemp is a potential security risk to your program", |
| 330 | ## RuntimeWarning, stacklevel=2) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 331 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 332 | if dir is None: |
| 333 | dir = gettempdir() |
| 334 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 335 | names = _get_candidate_names() |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 336 | for seq in range(TMP_MAX): |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 337 | name = next(names) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 338 | file = _os.path.join(dir, prefix + name + suffix) |
Guido van Rossum | b25615939 | 2003-11-10 02:16:36 +0000 | [diff] [blame] | 339 | if not _exists(file): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 340 | return file |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 341 | |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 342 | raise IOError(_errno.EEXIST, "No usable temporary filename found") |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 343 | |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 344 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 345 | class _TemporaryFileWrapper: |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 346 | """Temporary file wrapper |
| 347 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 348 | This class provides a wrapper around files opened for |
| 349 | temporary use. In particular, it seeks to automatically |
| 350 | remove the file when it is no longer needed. |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 351 | """ |
Tim Peters | a255a72 | 2001-12-18 22:32:40 +0000 | [diff] [blame] | 352 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 353 | def __init__(self, file, name, delete=True): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 354 | self.file = file |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 355 | self.name = name |
Tim Peters | 6ef966e | 2002-11-21 15:48:33 +0000 | [diff] [blame] | 356 | self.close_called = False |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 357 | self.delete = delete |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 358 | |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 359 | def __getattr__(self, name): |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 360 | # Attribute lookups are delegated to the underlying file |
| 361 | # and cached for non-numeric results |
| 362 | # (i.e. methods are cached, closed and friends are not) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 363 | file = self.__dict__['file'] |
| 364 | a = getattr(file, name) |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 365 | if not isinstance(a, int): |
Guido van Rossum | 6b708d5 | 1999-06-01 18:55:36 +0000 | [diff] [blame] | 366 | setattr(self, name, a) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 367 | return a |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 368 | |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 369 | # The underlying __enter__ method returns the wrong object |
| 370 | # (self.file) so override it to return the wrapper |
| 371 | def __enter__(self): |
| 372 | self.file.__enter__() |
| 373 | return self |
| 374 | |
Christian Heimes | 36d1f8e | 2008-02-28 22:21:11 +0000 | [diff] [blame] | 375 | # iter() doesn't use __getattr__ to find the __iter__ method |
Christian Heimes | c83b629 | 2008-02-28 21:10:17 +0000 | [diff] [blame] | 376 | def __iter__(self): |
Christian Heimes | 36d1f8e | 2008-02-28 22:21:11 +0000 | [diff] [blame] | 377 | return iter(self.file) |
Christian Heimes | c83b629 | 2008-02-28 21:10:17 +0000 | [diff] [blame] | 378 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 379 | # NT provides delete-on-close as a primitive, so we don't need |
| 380 | # the wrapper to do anything special. We still use it so that |
| 381 | # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile. |
| 382 | if _os.name != 'nt': |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 383 | # Cache the unlinker so we don't get spurious errors at |
| 384 | # shutdown when the module-level "os" is None'd out. Note |
| 385 | # that this must be referenced as self.unlink, because the |
| 386 | # name TemporaryFileWrapper may also get None'd out before |
| 387 | # __del__ is called. |
| 388 | unlink = _os.unlink |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 389 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 390 | def close(self): |
| 391 | if not self.close_called: |
Tim Peters | 6ef966e | 2002-11-21 15:48:33 +0000 | [diff] [blame] | 392 | self.close_called = True |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 393 | self.file.close() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 394 | if self.delete: |
| 395 | self.unlink(self.name) |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 396 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 397 | def __del__(self): |
| 398 | self.close() |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 399 | |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 400 | # Need to trap __exit__ as well to ensure the file gets |
| 401 | # deleted when used in a with statement |
| 402 | def __exit__(self, exc, value, tb): |
| 403 | result = self.file.__exit__(exc, value, tb) |
| 404 | self.close() |
| 405 | return result |
Benjamin Peterson | 98d23f2 | 2009-06-30 22:27:25 +0000 | [diff] [blame] | 406 | else: |
| 407 | def __exit__(self, exc, value, tb): |
Benjamin Peterson | 3f5de13 | 2009-07-01 15:47:07 +0000 | [diff] [blame] | 408 | self.file.__exit__(exc, value, tb) |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 409 | |
| 410 | |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 411 | def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, |
| 412 | newline=None, suffix="", prefix=template, |
| 413 | dir=None, delete=True): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 414 | """Create and return a temporary file. |
| 415 | Arguments: |
| 416 | 'prefix', 'suffix', 'dir' -- as for mkstemp. |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 417 | 'mode' -- the mode argument to io.open (default "w+b"). |
| 418 | 'buffering' -- the buffer size argument to io.open (default -1). |
| 419 | 'encoding' -- the encoding argument to io.open (default None) |
| 420 | 'newline' -- the newline argument to io.open (default None) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 421 | 'delete' -- whether the file is deleted on close (default True). |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 422 | The file is created as mkstemp() would do it. |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 423 | |
Raymond Hettinger | faa10eb | 2005-01-11 15:33:03 +0000 | [diff] [blame] | 424 | Returns an object with a file-like interface; the name of the file |
| 425 | is accessible as file.name. The file will be automatically deleted |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 426 | when it is closed unless the 'delete' argument is set to False. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 427 | """ |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 428 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 429 | if dir is None: |
| 430 | dir = gettempdir() |
| 431 | |
Amaury Forgeot d'Arc | 7d0bddd | 2009-11-30 00:08:56 +0000 | [diff] [blame] | 432 | flags = _bin_openflags |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 433 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 434 | # Setting O_TEMPORARY in the flags causes the OS to delete |
| 435 | # the file when it is closed. This is only supported by Windows. |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 436 | if _os.name == 'nt' and delete: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 437 | flags |= _os.O_TEMPORARY |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 438 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 439 | (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags) |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 440 | file = _io.open(fd, mode, buffering=buffering, |
| 441 | newline=newline, encoding=encoding) |
| 442 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 443 | return _TemporaryFileWrapper(file, name, delete) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 444 | |
Jason Tishler | 80c02af | 2002-08-14 15:10:09 +0000 | [diff] [blame] | 445 | if _os.name != 'posix' or _os.sys.platform == 'cygwin': |
| 446 | # On non-POSIX and Cygwin systems, assume that we cannot unlink a file |
| 447 | # while it is open. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 448 | TemporaryFile = NamedTemporaryFile |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 449 | |
| 450 | else: |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 451 | def TemporaryFile(mode='w+b', buffering=-1, encoding=None, |
| 452 | newline=None, suffix="", prefix=template, |
| 453 | dir=None): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 454 | """Create and return a temporary file. |
| 455 | Arguments: |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 456 | 'prefix', 'suffix', 'dir' -- as for mkstemp. |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 457 | 'mode' -- the mode argument to io.open (default "w+b"). |
| 458 | 'buffering' -- the buffer size argument to io.open (default -1). |
| 459 | 'encoding' -- the encoding argument to io.open (default None) |
| 460 | 'newline' -- the newline argument to io.open (default None) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 461 | The file is created as mkstemp() would do it. |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 462 | |
Raymond Hettinger | faa10eb | 2005-01-11 15:33:03 +0000 | [diff] [blame] | 463 | Returns an object with a file-like interface. The file has no |
| 464 | name, and will cease to exist when it is closed. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 465 | """ |
| 466 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 467 | if dir is None: |
| 468 | dir = gettempdir() |
| 469 | |
Amaury Forgeot d'Arc | 7d0bddd | 2009-11-30 00:08:56 +0000 | [diff] [blame] | 470 | flags = _bin_openflags |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 471 | |
| 472 | (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags) |
| 473 | try: |
| 474 | _os.unlink(name) |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 475 | return _io.open(fd, mode, buffering=buffering, |
| 476 | newline=newline, encoding=encoding) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 477 | except: |
| 478 | _os.close(fd) |
| 479 | raise |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 480 | |
| 481 | class SpooledTemporaryFile: |
| 482 | """Temporary file wrapper, specialized to switch from |
| 483 | StringIO to a real file when it exceeds a certain size or |
| 484 | when a fileno is needed. |
| 485 | """ |
| 486 | _rolled = False |
| 487 | |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 488 | def __init__(self, max_size=0, mode='w+b', buffering=-1, |
| 489 | encoding=None, newline=None, |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 490 | suffix="", prefix=template, dir=None): |
Guido van Rossum | 9a63470 | 2007-07-09 10:24:45 +0000 | [diff] [blame] | 491 | if 'b' in mode: |
| 492 | self._file = _io.BytesIO() |
| 493 | else: |
Guido van Rossum | 5d21255 | 2007-10-29 16:42:51 +0000 | [diff] [blame] | 494 | # Setting newline="\n" avoids newline translation; |
| 495 | # this is important because otherwise on Windows we'd |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 496 | # hget double newline translation upon rollover(). |
Alexandre Vassalotti | 3ade6f9 | 2008-06-12 01:13:54 +0000 | [diff] [blame] | 497 | self._file = _io.StringIO(newline="\n") |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 498 | self._max_size = max_size |
| 499 | self._rolled = False |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 500 | self._TemporaryFileArgs = {'mode': mode, 'buffering': buffering, |
| 501 | 'suffix': suffix, 'prefix': prefix, |
| 502 | 'encoding': encoding, 'newline': newline, |
| 503 | 'dir': dir} |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 504 | |
| 505 | def _check(self, file): |
| 506 | if self._rolled: return |
| 507 | max_size = self._max_size |
| 508 | if max_size and file.tell() > max_size: |
| 509 | self.rollover() |
| 510 | |
| 511 | def rollover(self): |
| 512 | if self._rolled: return |
| 513 | file = self._file |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 514 | newfile = self._file = TemporaryFile(**self._TemporaryFileArgs) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 515 | del self._TemporaryFileArgs |
| 516 | |
| 517 | newfile.write(file.getvalue()) |
| 518 | newfile.seek(file.tell(), 0) |
| 519 | |
| 520 | self._rolled = True |
| 521 | |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 522 | # The method caching trick from NamedTemporaryFile |
| 523 | # won't work here, because _file may change from a |
| 524 | # _StringIO instance to a real file. So we list |
| 525 | # all the methods directly. |
| 526 | |
| 527 | # Context management protocol |
| 528 | def __enter__(self): |
| 529 | if self._file.closed: |
| 530 | raise ValueError("Cannot enter context with closed file") |
| 531 | return self |
| 532 | |
| 533 | def __exit__(self, exc, value, tb): |
| 534 | self._file.close() |
| 535 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 536 | # file protocol |
| 537 | def __iter__(self): |
| 538 | return self._file.__iter__() |
| 539 | |
| 540 | def close(self): |
| 541 | self._file.close() |
| 542 | |
| 543 | @property |
| 544 | def closed(self): |
| 545 | return self._file.closed |
| 546 | |
| 547 | @property |
| 548 | def encoding(self): |
| 549 | return self._file.encoding |
| 550 | |
| 551 | def fileno(self): |
| 552 | self.rollover() |
| 553 | return self._file.fileno() |
| 554 | |
| 555 | def flush(self): |
| 556 | self._file.flush() |
| 557 | |
| 558 | def isatty(self): |
| 559 | return self._file.isatty() |
| 560 | |
| 561 | @property |
| 562 | def mode(self): |
| 563 | return self._file.mode |
| 564 | |
| 565 | @property |
| 566 | def name(self): |
| 567 | return self._file.name |
| 568 | |
| 569 | @property |
| 570 | def newlines(self): |
| 571 | return self._file.newlines |
| 572 | |
| 573 | def next(self): |
| 574 | return self._file.next |
| 575 | |
| 576 | def read(self, *args): |
| 577 | return self._file.read(*args) |
| 578 | |
| 579 | def readline(self, *args): |
| 580 | return self._file.readline(*args) |
| 581 | |
| 582 | def readlines(self, *args): |
| 583 | return self._file.readlines(*args) |
| 584 | |
| 585 | def seek(self, *args): |
| 586 | self._file.seek(*args) |
| 587 | |
| 588 | @property |
| 589 | def softspace(self): |
| 590 | return self._file.softspace |
| 591 | |
| 592 | def tell(self): |
| 593 | return self._file.tell() |
| 594 | |
| 595 | def truncate(self): |
| 596 | self._file.truncate() |
| 597 | |
| 598 | def write(self, s): |
| 599 | file = self._file |
| 600 | rv = file.write(s) |
| 601 | self._check(file) |
| 602 | return rv |
| 603 | |
| 604 | def writelines(self, iterable): |
| 605 | file = self._file |
| 606 | rv = file.writelines(iterable) |
| 607 | self._check(file) |
| 608 | return rv |
| 609 | |
| 610 | def xreadlines(self, *args): |
| 611 | return self._file.xreadlines(*args) |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 612 | |
| 613 | |
| 614 | class TemporaryDirectory(object): |
| 615 | """Create and return a temporary directory. This has the same |
| 616 | behavior as mkdtemp but can be used as a context manager. For |
| 617 | example: |
| 618 | |
| 619 | with TemporaryDirectory() as tmpdir: |
| 620 | ... |
| 621 | |
| 622 | Upon exiting the context, the directory and everthing contained |
| 623 | in it are removed. |
| 624 | """ |
| 625 | |
| 626 | def __init__(self, suffix="", prefix=template, dir=None): |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 627 | self._closed = False |
Nick Coghlan | 6b22f3f | 2010-12-12 15:24:21 +0000 | [diff] [blame] | 628 | self.name = None # Handle mkdtemp throwing an exception |
| 629 | self.name = mkdtemp(suffix, prefix, dir) |
| 630 | |
| 631 | def __repr__(self): |
| 632 | return "<{} {!r}>".format(self.__class__.__name__, self.name) |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 633 | |
| 634 | def __enter__(self): |
| 635 | return self.name |
| 636 | |
Nick Coghlan | 6b22f3f | 2010-12-12 15:24:21 +0000 | [diff] [blame] | 637 | def cleanup(self, _warn=False): |
| 638 | if self.name and not self._closed: |
| 639 | try: |
| 640 | self._rmtree(self.name) |
| 641 | except (TypeError, AttributeError) as ex: |
| 642 | # Issue #10188: Emit a warning on stderr |
| 643 | # if the directory could not be cleaned |
| 644 | # up due to missing globals |
| 645 | if "None" not in str(ex): |
| 646 | raise |
| 647 | print("ERROR: {!r} while cleaning up {!r}".format(ex, self,), |
| 648 | file=_sys.stderr) |
| 649 | return |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 650 | self._closed = True |
Nick Coghlan | 6b22f3f | 2010-12-12 15:24:21 +0000 | [diff] [blame] | 651 | if _warn: |
| 652 | self._warn("Implicitly cleaning up {!r}".format(self), |
| 653 | ResourceWarning) |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 654 | |
| 655 | def __exit__(self, exc, value, tb): |
| 656 | self.cleanup() |
| 657 | |
Nick Coghlan | 6b22f3f | 2010-12-12 15:24:21 +0000 | [diff] [blame] | 658 | def __del__(self): |
| 659 | # Issue a ResourceWarning if implicit cleanup needed |
| 660 | self.cleanup(_warn=True) |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 661 | |
| 662 | # XXX (ncoghlan): The following code attempts to make |
| 663 | # this class tolerant of the module nulling out process |
| 664 | # that happens during CPython interpreter shutdown |
| 665 | # Alas, it doesn't actually manage it. See issue #10188 |
| 666 | _listdir = staticmethod(_os.listdir) |
| 667 | _path_join = staticmethod(_os.path.join) |
| 668 | _isdir = staticmethod(_os.path.isdir) |
Charles-François Natali | def3543 | 2011-07-29 18:59:24 +0200 | [diff] [blame] | 669 | _islink = staticmethod(_os.path.islink) |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 670 | _remove = staticmethod(_os.remove) |
| 671 | _rmdir = staticmethod(_os.rmdir) |
| 672 | _os_error = _os.error |
Nick Coghlan | 6b22f3f | 2010-12-12 15:24:21 +0000 | [diff] [blame] | 673 | _warn = _warnings.warn |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 674 | |
| 675 | def _rmtree(self, path): |
| 676 | # Essentially a stripped down version of shutil.rmtree. We can't |
| 677 | # use globals because they may be None'ed out at shutdown. |
| 678 | for name in self._listdir(path): |
| 679 | fullname = self._path_join(path, name) |
| 680 | try: |
Charles-François Natali | def3543 | 2011-07-29 18:59:24 +0200 | [diff] [blame] | 681 | isdir = self._isdir(fullname) and not self._islink(fullname) |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 682 | except self._os_error: |
| 683 | isdir = False |
| 684 | if isdir: |
| 685 | self._rmtree(fullname) |
| 686 | else: |
| 687 | try: |
| 688 | self._remove(fullname) |
| 689 | except self._os_error: |
| 690 | pass |
| 691 | try: |
| 692 | self._rmdir(path) |
| 693 | except self._os_error: |
| 694 | pass |