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