blob: 7b6821240f2b4bfa40efaa0a43b623ed623dee1b [file] [log] [blame]
Guido van Rossum0e548712002-08-09 16:14:33 +00001"""Temporary files.
Guido van Rossume7b146f2000-02-04 15:28:42 +00002
Guido van Rossum0e548712002-08-09 16:14:33 +00003This module provides generic, low- and high-level interfaces for
Yury Selivanov0b866602014-09-26 17:08:21 -04004creating temporary files and directories. All of the interfaces
5provided by this module can be used without fear of race conditions
6except for 'mktemp'. 'mktemp' is subject to race conditions and
7should not be used; it is provided for backward compatibility only.
Guido van Rossumeee94981991-11-12 15:38:08 +00008
Gregory P. Smithad577b92015-05-22 16:18:14 -07009The default path names are returned as str. If you supply bytes as
10input, all return values will be in bytes. Ex:
11
12 >>> tempfile.mkstemp()
13 (4, '/tmp/tmptpu9nin8')
14 >>> tempfile.mkdtemp(suffix=b'')
15 b'/tmp/tmppbi8f0hy'
16
Guido van Rossum0e548712002-08-09 16:14:33 +000017This module also provides some data items to the user:
Guido van Rossumeee94981991-11-12 15:38:08 +000018
Guido van Rossum0e548712002-08-09 16:14:33 +000019 TMP_MAX - maximum number of names that will be tried before
20 giving up.
Guido van Rossum0e548712002-08-09 16:14:33 +000021 tempdir - If this is set to a string before the first use of
22 any routine from this module, it will be considered as
23 another candidate location to store temporary files.
24"""
Skip Montanaro40fc1602001-03-01 04:27:19 +000025
Guido van Rossum0e548712002-08-09 16:14:33 +000026__all__ = [
27 "NamedTemporaryFile", "TemporaryFile", # high level safe interfaces
Nick Coghlan543af752010-10-24 11:23:25 +000028 "SpooledTemporaryFile", "TemporaryDirectory",
Guido van Rossum0e548712002-08-09 16:14:33 +000029 "mkstemp", "mkdtemp", # low level safe interfaces
30 "mktemp", # deprecated unsafe interface
31 "TMP_MAX", "gettempprefix", # constants
Gregory P. Smithad577b92015-05-22 16:18:14 -070032 "tempdir", "gettempdir",
33 "gettempprefixb", "gettempdirb",
Guido van Rossum0e548712002-08-09 16:14:33 +000034 ]
Guido van Rossum41f95031992-03-31 19:02:01 +000035
Tim Peters4fd5a062002-01-28 23:11:23 +000036
Guido van Rossum0e548712002-08-09 16:14:33 +000037# Imports.
Tim Peters4fd5a062002-01-28 23:11:23 +000038
Antoine Pitrou17c93262013-12-21 22:14:56 +010039import functools as _functools
Nick Coghlan6b22f3f2010-12-12 15:24:21 +000040import warnings as _warnings
Guido van Rossum9a634702007-07-09 10:24:45 +000041import io as _io
Guido van Rossum0e548712002-08-09 16:14:33 +000042import os as _os
Serhiy Storchaka99e033b2014-01-27 11:18:27 +020043import shutil as _shutil
Serhiy Storchaka7451a722013-02-09 22:25:49 +020044import errno as _errno
Guido van Rossum0e548712002-08-09 16:14:33 +000045from random import Random as _Random
Steve Dower60419a72019-06-24 08:42:54 -070046import sys as _sys
Guido van Rossum48b069a2020-04-07 09:50:06 -070047import types as _types
Serhiy Storchakaa28632b2014-01-27 11:21:54 +020048import weakref as _weakref
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020049import _thread
Guido van Rossuma0934242002-12-30 22:36:09 +000050_allocate_lock = _thread.allocate_lock
Guido van Rossum0e548712002-08-09 16:14:33 +000051
52_text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL
Tim Petersa0d55de2002-08-09 18:01:01 +000053if hasattr(_os, 'O_NOFOLLOW'):
54 _text_openflags |= _os.O_NOFOLLOW
Guido van Rossum0e548712002-08-09 16:14:33 +000055
56_bin_openflags = _text_openflags
Tim Petersa0d55de2002-08-09 18:01:01 +000057if hasattr(_os, 'O_BINARY'):
58 _bin_openflags |= _os.O_BINARY
Guido van Rossum0e548712002-08-09 16:14:33 +000059
60if hasattr(_os, 'TMP_MAX'):
61 TMP_MAX = _os.TMP_MAX
62else:
63 TMP_MAX = 10000
64
Gregory P. Smithad577b92015-05-22 16:18:14 -070065# This variable _was_ unused for legacy reasons, see issue 10354.
66# But as of 3.5 we actually use it at runtime so changing it would
67# have a possibly desirable side effect... But we do not want to support
68# that as an API. It is undocumented on purpose. Do not depend on this.
Tim Petersbd7b4c72002-08-13 23:33:56 +000069template = "tmp"
Guido van Rossum0e548712002-08-09 16:14:33 +000070
Guido van Rossum0e548712002-08-09 16:14:33 +000071# Internal routines.
72
73_once_lock = _allocate_lock()
74
Guido van Rossumb256159392003-11-10 02:16:36 +000075
76def _exists(fn):
77 try:
Anthony Sottile8377cd42019-02-25 14:32:27 -080078 _os.lstat(fn)
Florent Xicluna68f71a32011-10-28 16:06:23 +020079 except OSError:
Guido van Rossumb256159392003-11-10 02:16:36 +000080 return False
81 else:
82 return True
83
Gregory P. Smithad577b92015-05-22 16:18:14 -070084
85def _infer_return_type(*args):
86 """Look at the type of all args and divine their implied return type."""
87 return_type = None
88 for arg in args:
89 if arg is None:
90 continue
Miss Islington (bot)64e83c72021-10-20 14:27:30 -070091
92 if isinstance(arg, _os.PathLike):
93 arg = _os.fspath(arg)
94
Gregory P. Smithad577b92015-05-22 16:18:14 -070095 if isinstance(arg, bytes):
96 if return_type is str:
97 raise TypeError("Can't mix bytes and non-bytes in "
98 "path components.")
99 return_type = bytes
100 else:
101 if return_type is bytes:
102 raise TypeError("Can't mix bytes and non-bytes in "
103 "path components.")
104 return_type = str
105 if return_type is None:
Eric L9c792742021-03-03 21:36:22 +0100106 if tempdir is None or isinstance(tempdir, str):
107 return str # tempfile APIs return a str by default.
108 else:
109 # we could check for bytes but it'll fail later on anyway
110 return bytes
Gregory P. Smithad577b92015-05-22 16:18:14 -0700111 return return_type
112
113
114def _sanitize_params(prefix, suffix, dir):
115 """Common parameter processing for most APIs in this module."""
116 output_type = _infer_return_type(prefix, suffix, dir)
117 if suffix is None:
118 suffix = output_type()
119 if prefix is None:
120 if output_type is str:
121 prefix = template
122 else:
123 prefix = _os.fsencode(template)
124 if dir is None:
125 if output_type is str:
126 dir = gettempdir()
127 else:
128 dir = gettempdirb()
129 return prefix, suffix, dir, output_type
130
131
Victor Stinner1e62bf12017-04-19 22:59:51 +0200132class _RandomNameSequence:
133 """An instance of _RandomNameSequence generates an endless
134 sequence of unpredictable strings which can safely be incorporated
Wolfgang Maier9c463ec2018-04-09 02:42:39 +0200135 into file names. Each string is eight characters long. Multiple
Victor Stinner1e62bf12017-04-19 22:59:51 +0200136 threads can safely use the same instance at the same time.
137
138 _RandomNameSequence is an iterator."""
Guido van Rossum0e548712002-08-09 16:14:33 +0000139
Inada Naoki43ca0842020-10-31 11:15:38 +0900140 characters = "abcdefghijklmnopqrstuvwxyz0123456789_"
141
142 @property
143 def rng(self):
144 cur_pid = _os.getpid()
145 if cur_pid != getattr(self, '_rng_pid', None):
146 self._rng = _Random()
147 self._rng_pid = cur_pid
148 return self._rng
Victor Stinner1e62bf12017-04-19 22:59:51 +0200149
150 def __iter__(self):
151 return self
152
153 def __next__(self):
Inada Naokid2810052020-11-01 20:02:03 +0900154 return ''.join(self.rng.choices(self.characters, k=8))
Guido van Rossum0e548712002-08-09 16:14:33 +0000155
156def _candidate_tempdir_list():
157 """Generate a list of candidate temporary directories which
158 _get_default_tempdir will try."""
159
160 dirlist = []
161
162 # First, try the environment.
163 for envname in 'TMPDIR', 'TEMP', 'TMP':
164 dirname = _os.getenv(envname)
165 if dirname: dirlist.append(dirname)
166
167 # Failing that, try OS-specific locations.
Alexandre Vassalottieca20b62008-05-16 02:54:33 +0000168 if _os.name == 'nt':
Steve Dowere5f41d22018-05-16 17:50:29 -0400169 dirlist.extend([ _os.path.expanduser(r'~\AppData\Local\Temp'),
170 _os.path.expandvars(r'%SYSTEMROOT%\Temp'),
171 r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
Guido van Rossum0e548712002-08-09 16:14:33 +0000172 else:
173 dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
174
175 # As a last resort, the current directory.
176 try:
177 dirlist.append(_os.getcwd())
Florent Xicluna68f71a32011-10-28 16:06:23 +0200178 except (AttributeError, OSError):
Guido van Rossum0e548712002-08-09 16:14:33 +0000179 dirlist.append(_os.curdir)
180
181 return dirlist
Tim Petersa0d55de2002-08-09 18:01:01 +0000182
Guido van Rossum0e548712002-08-09 16:14:33 +0000183def _get_default_tempdir():
184 """Calculate the default directory to use for temporary files.
Guido van Rossume888cdc2002-08-17 14:50:24 +0000185 This routine should be called exactly once.
Guido van Rossum0e548712002-08-09 16:14:33 +0000186
187 We determine whether or not a candidate temp dir is usable by
188 trying to create and write to a file in that directory. If this
189 is successful, the test file is deleted. To prevent denial of
190 service, the name of the test file must be randomized."""
191
192 namer = _RandomNameSequence()
193 dirlist = _candidate_tempdir_list()
Guido van Rossum0e548712002-08-09 16:14:33 +0000194
195 for dir in dirlist:
196 if dir != _os.curdir:
Tim Golden6d09f092013-10-25 18:38:16 +0100197 dir = _os.path.abspath(dir)
Guido van Rossum0e548712002-08-09 16:14:33 +0000198 # Try only a few names per directory.
Guido van Rossum805365e2007-05-07 22:24:25 +0000199 for seq in range(100):
Georg Brandla18af4e2007-04-21 15:47:16 +0000200 name = next(namer)
Guido van Rossum0e548712002-08-09 16:14:33 +0000201 filename = _os.path.join(dir, name)
202 try:
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000203 fd = _os.open(filename, _bin_openflags, 0o600)
Serhiy Storchakaf6b361e2013-02-13 00:35:30 +0200204 try:
205 try:
Serhiy Storchaka76a2ed12013-02-13 00:59:26 +0200206 with _io.open(fd, 'wb', closefd=False) as fp:
207 fp.write(b'blat')
Serhiy Storchakaf6b361e2013-02-13 00:35:30 +0200208 finally:
209 _os.close(fd)
210 finally:
211 _os.unlink(filename)
Guido van Rossum0e548712002-08-09 16:14:33 +0000212 return dir
Florent Xicluna68f71a32011-10-28 16:06:23 +0200213 except FileExistsError:
Guido van Rossum0e548712002-08-09 16:14:33 +0000214 pass
Serhiy Storchaka5d6b7b12015-05-20 00:11:48 +0300215 except PermissionError:
216 # This exception is thrown when a directory with the chosen name
217 # already exists on windows.
218 if (_os.name == 'nt' and _os.path.isdir(dir) and
219 _os.access(dir, _os.W_OK)):
220 continue
221 break # no point trying more names in this directory
Florent Xicluna68f71a32011-10-28 16:06:23 +0200222 except OSError:
223 break # no point trying more names in this directory
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200224 raise FileNotFoundError(_errno.ENOENT,
225 "No usable temporary directory found in %s" %
226 dirlist)
Guido van Rossum0e548712002-08-09 16:14:33 +0000227
Guido van Rossume888cdc2002-08-17 14:50:24 +0000228_name_sequence = None
229
Guido van Rossum0e548712002-08-09 16:14:33 +0000230def _get_candidate_names():
231 """Common setup sequence for all user-callable interfaces."""
232
Guido van Rossume888cdc2002-08-17 14:50:24 +0000233 global _name_sequence
234 if _name_sequence is None:
235 _once_lock.acquire()
236 try:
237 if _name_sequence is None:
238 _name_sequence = _RandomNameSequence()
239 finally:
240 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000241 return _name_sequence
Guido van Rossum41f95031992-03-31 19:02:01 +0000242
243
Gregory P. Smithad577b92015-05-22 16:18:14 -0700244def _mkstemp_inner(dir, pre, suf, flags, output_type):
Guido van Rossum0e548712002-08-09 16:14:33 +0000245 """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
Tim Peters9fadfb02001-01-13 03:04:02 +0000246
Guido van Rossum0e548712002-08-09 16:14:33 +0000247 names = _get_candidate_names()
Gregory P. Smithad577b92015-05-22 16:18:14 -0700248 if output_type is bytes:
249 names = map(_os.fsencode, names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000250
Guido van Rossum805365e2007-05-07 22:24:25 +0000251 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000252 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000253 file = _os.path.join(dir, pre + name + suf)
Steve Dower60419a72019-06-24 08:42:54 -0700254 _sys.audit("tempfile.mkstemp", file)
Guido van Rossum0e548712002-08-09 16:14:33 +0000255 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000256 fd = _os.open(file, flags, 0o600)
Florent Xicluna68f71a32011-10-28 16:06:23 +0200257 except FileExistsError:
258 continue # try again
Eli Benderskyf315df32013-09-06 06:11:19 -0700259 except PermissionError:
260 # This exception is thrown when a directory with the chosen name
261 # already exists on windows.
Serhiy Storchaka5d6b7b12015-05-20 00:11:48 +0300262 if (_os.name == 'nt' and _os.path.isdir(dir) and
263 _os.access(dir, _os.W_OK)):
Eli Benderskyf315df32013-09-06 06:11:19 -0700264 continue
265 else:
266 raise
Gregory P. Smithad577b92015-05-22 16:18:14 -0700267 return (fd, _os.path.abspath(file))
Guido van Rossum0e548712002-08-09 16:14:33 +0000268
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200269 raise FileExistsError(_errno.EEXIST,
270 "No usable temporary file name found")
Tim Petersa0d55de2002-08-09 18:01:01 +0000271
Guido van Rossum0e548712002-08-09 16:14:33 +0000272
273# User visible interfaces.
Guido van Rossumb0e57181998-10-14 20:27:05 +0000274
Guido van Rossum41f95031992-03-31 19:02:01 +0000275def gettempprefix():
Eric L9c792742021-03-03 21:36:22 +0100276 """The default prefix for temporary directories as string."""
277 return _os.fsdecode(template)
Tim Peters9fadfb02001-01-13 03:04:02 +0000278
Gregory P. Smithad577b92015-05-22 16:18:14 -0700279def gettempprefixb():
280 """The default prefix for temporary directories as bytes."""
Eric L9c792742021-03-03 21:36:22 +0100281 return _os.fsencode(template)
Gregory P. Smithad577b92015-05-22 16:18:14 -0700282
Guido van Rossume888cdc2002-08-17 14:50:24 +0000283tempdir = None
284
Eric L9c792742021-03-03 21:36:22 +0100285def _gettempdir():
286 """Private accessor for tempfile.tempdir."""
Guido van Rossume888cdc2002-08-17 14:50:24 +0000287 global tempdir
288 if tempdir is None:
289 _once_lock.acquire()
290 try:
291 if tempdir is None:
292 tempdir = _get_default_tempdir()
293 finally:
294 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000295 return tempdir
296
Eric L9c792742021-03-03 21:36:22 +0100297def gettempdir():
298 """Returns tempfile.tempdir as str."""
299 return _os.fsdecode(_gettempdir())
300
Gregory P. Smithad577b92015-05-22 16:18:14 -0700301def gettempdirb():
Eric L9c792742021-03-03 21:36:22 +0100302 """Returns tempfile.tempdir as bytes."""
303 return _os.fsencode(_gettempdir())
Gregory P. Smithad577b92015-05-22 16:18:14 -0700304
305def mkstemp(suffix=None, prefix=None, dir=None, text=False):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000306 """User-callable function to create and return a unique temporary
Guido van Rossum0e548712002-08-09 16:14:33 +0000307 file. The return value is a pair (fd, name) where fd is the
308 file descriptor returned by os.open, and name is the filename.
309
Martin Panter9b566c32015-11-07 00:32:50 +0000310 If 'suffix' is not None, the file name will end with that suffix,
Guido van Rossum0e548712002-08-09 16:14:33 +0000311 otherwise there will be no suffix.
312
Martin Panter9b566c32015-11-07 00:32:50 +0000313 If 'prefix' is not None, the file name will begin with that prefix,
Guido van Rossum0e548712002-08-09 16:14:33 +0000314 otherwise a default prefix is used.
315
Martin Panter9b566c32015-11-07 00:32:50 +0000316 If 'dir' is not None, the file will be created in that directory,
Guido van Rossum0e548712002-08-09 16:14:33 +0000317 otherwise a default directory is used.
318
Tim Peters04490bf2002-08-14 15:41:26 +0000319 If 'text' is specified and true, the file is opened in text
Rishav Kundue55de682020-08-14 07:03:14 +0530320 mode. Else (the default) the file is opened in binary mode.
Guido van Rossum0e548712002-08-09 16:14:33 +0000321
Martin Panter9b566c32015-11-07 00:32:50 +0000322 If any of 'suffix', 'prefix' and 'dir' are not None, they must be the
323 same type. If they are bytes, the returned name will be bytes; str
324 otherwise.
Gregory P. Smithad577b92015-05-22 16:18:14 -0700325
Guido van Rossum0e548712002-08-09 16:14:33 +0000326 The file is readable and writable only by the creating user ID.
327 If the operating system uses permission bits to indicate whether a
328 file is executable, the file is executable by no one. The file
329 descriptor is not inherited by children of this process.
330
331 Caller is responsible for deleting the file when done with it.
Tim Peters9fadfb02001-01-13 03:04:02 +0000332 """
333
Gregory P. Smithad577b92015-05-22 16:18:14 -0700334 prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
Guido van Rossume888cdc2002-08-17 14:50:24 +0000335
Tim Peters04490bf2002-08-14 15:41:26 +0000336 if text:
Guido van Rossum0e548712002-08-09 16:14:33 +0000337 flags = _text_openflags
Tim Peters04490bf2002-08-14 15:41:26 +0000338 else:
339 flags = _bin_openflags
Guido van Rossum0e548712002-08-09 16:14:33 +0000340
Gregory P. Smithad577b92015-05-22 16:18:14 -0700341 return _mkstemp_inner(dir, prefix, suffix, flags, output_type)
Guido van Rossumcff34541992-01-14 18:31:56 +0000342
Guido van Rossumeee94981991-11-12 15:38:08 +0000343
Gregory P. Smithad577b92015-05-22 16:18:14 -0700344def mkdtemp(suffix=None, prefix=None, dir=None):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000345 """User-callable function to create and return a unique temporary
Guido van Rossum0e548712002-08-09 16:14:33 +0000346 directory. The return value is the pathname of the directory.
347
Tim Peters04490bf2002-08-14 15:41:26 +0000348 Arguments are as for mkstemp, except that the 'text' argument is
Guido van Rossum0e548712002-08-09 16:14:33 +0000349 not accepted.
350
351 The directory is readable, writable, and searchable only by the
352 creating user.
353
354 Caller is responsible for deleting the directory when done with it.
355 """
356
Gregory P. Smithad577b92015-05-22 16:18:14 -0700357 prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
Guido van Rossume888cdc2002-08-17 14:50:24 +0000358
Guido van Rossum0e548712002-08-09 16:14:33 +0000359 names = _get_candidate_names()
Gregory P. Smithad577b92015-05-22 16:18:14 -0700360 if output_type is bytes:
361 names = map(_os.fsencode, names)
Tim Petersa0d55de2002-08-09 18:01:01 +0000362
Guido van Rossum805365e2007-05-07 22:24:25 +0000363 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000364 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000365 file = _os.path.join(dir, prefix + name + suffix)
Steve Dower60419a72019-06-24 08:42:54 -0700366 _sys.audit("tempfile.mkdtemp", file)
Guido van Rossum0e548712002-08-09 16:14:33 +0000367 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000368 _os.mkdir(file, 0o700)
Florent Xicluna68f71a32011-10-28 16:06:23 +0200369 except FileExistsError:
370 continue # try again
Serhiy Storchaka5d6b7b12015-05-20 00:11:48 +0300371 except PermissionError:
372 # This exception is thrown when a directory with the chosen name
373 # already exists on windows.
374 if (_os.name == 'nt' and _os.path.isdir(dir) and
375 _os.access(dir, _os.W_OK)):
376 continue
377 else:
378 raise
Gregory P. Smithad577b92015-05-22 16:18:14 -0700379 return file
Guido van Rossum0e548712002-08-09 16:14:33 +0000380
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200381 raise FileExistsError(_errno.EEXIST,
382 "No usable temporary directory name found")
Guido van Rossum0e548712002-08-09 16:14:33 +0000383
Guido van Rossume888cdc2002-08-17 14:50:24 +0000384def mktemp(suffix="", prefix=template, dir=None):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000385 """User-callable function to return a unique temporary file name. The
Guido van Rossum0e548712002-08-09 16:14:33 +0000386 file is not created.
387
Martin Panter9b566c32015-11-07 00:32:50 +0000388 Arguments are similar to mkstemp, except that the 'text' argument is
389 not accepted, and suffix=None, prefix=None and bytes file names are not
390 supported.
Guido van Rossum0e548712002-08-09 16:14:33 +0000391
Gregory P. Smithad577b92015-05-22 16:18:14 -0700392 THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may
393 refer to a file that did not exist at some point, but by the time
Guido van Rossum0e548712002-08-09 16:14:33 +0000394 you get around to creating it, someone else may have beaten you to
395 the punch.
396 """
397
Guido van Rossum44f602d2002-11-22 15:56:29 +0000398## from warnings import warn as _warn
399## _warn("mktemp is a potential security risk to your program",
400## RuntimeWarning, stacklevel=2)
Guido van Rossum0e548712002-08-09 16:14:33 +0000401
Guido van Rossume888cdc2002-08-17 14:50:24 +0000402 if dir is None:
403 dir = gettempdir()
404
Guido van Rossum0e548712002-08-09 16:14:33 +0000405 names = _get_candidate_names()
Guido van Rossum805365e2007-05-07 22:24:25 +0000406 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000407 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000408 file = _os.path.join(dir, prefix + name + suffix)
Guido van Rossumb256159392003-11-10 02:16:36 +0000409 if not _exists(file):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000410 return file
Guido van Rossumca549821997-08-12 18:00:12 +0000411
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200412 raise FileExistsError(_errno.EEXIST,
413 "No usable temporary filename found")
Guido van Rossumca549821997-08-12 18:00:12 +0000414
Christian Heimes3ecfea712008-02-09 20:51:34 +0000415
Antoine Pitrou17c93262013-12-21 22:14:56 +0100416class _TemporaryFileCloser:
417 """A separate object allowing proper closing of a temporary file's
418 underlying file object, without adding a __del__ method to the
419 temporary file."""
Tim Petersa255a722001-12-18 22:32:40 +0000420
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200421 file = None # Set here since __del__ checks it
Serhiy Storchaka99e033b2014-01-27 11:18:27 +0200422 close_called = False
423
Guido van Rossumd8faa362007-04-27 19:54:29 +0000424 def __init__(self, file, name, delete=True):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000425 self.file = file
Guido van Rossum0e548712002-08-09 16:14:33 +0000426 self.name = name
Guido van Rossumd8faa362007-04-27 19:54:29 +0000427 self.delete = delete
Guido van Rossumca549821997-08-12 18:00:12 +0000428
Guido van Rossum0e548712002-08-09 16:14:33 +0000429 # NT provides delete-on-close as a primitive, so we don't need
430 # the wrapper to do anything special. We still use it so that
431 # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
432 if _os.name != 'nt':
Guido van Rossum0e548712002-08-09 16:14:33 +0000433 # Cache the unlinker so we don't get spurious errors at
434 # shutdown when the module-level "os" is None'd out. Note
435 # that this must be referenced as self.unlink, because the
436 # name TemporaryFileWrapper may also get None'd out before
437 # __del__ is called.
Tim Peters1baa22a2001-01-12 10:02:46 +0000438
Serhiy Storchaka99e033b2014-01-27 11:18:27 +0200439 def close(self, unlink=_os.unlink):
440 if not self.close_called and self.file is not None:
Tim Peters6ef966e2002-11-21 15:48:33 +0000441 self.close_called = True
Serhiy Storchaka7e7a3db2015-04-10 13:24:41 +0300442 try:
443 self.file.close()
444 finally:
445 if self.delete:
446 unlink(self.name)
Tim Peters1baa22a2001-01-12 10:02:46 +0000447
Antoine Pitrou17c93262013-12-21 22:14:56 +0100448 # Need to ensure the file is deleted on __del__
Guido van Rossum0e548712002-08-09 16:14:33 +0000449 def __del__(self):
450 self.close()
Tim Peters1baa22a2001-01-12 10:02:46 +0000451
Benjamin Peterson98d23f22009-06-30 22:27:25 +0000452 else:
Antoine Pitrou17c93262013-12-21 22:14:56 +0100453 def close(self):
454 if not self.close_called:
455 self.close_called = True
456 self.file.close()
457
458
459class _TemporaryFileWrapper:
460 """Temporary file wrapper
461
462 This class provides a wrapper around files opened for
463 temporary use. In particular, it seeks to automatically
464 remove the file when it is no longer needed.
465 """
466
467 def __init__(self, file, name, delete=True):
468 self.file = file
469 self.name = name
470 self.delete = delete
471 self._closer = _TemporaryFileCloser(file, name, delete)
472
473 def __getattr__(self, name):
474 # Attribute lookups are delegated to the underlying file
475 # and cached for non-numeric results
476 # (i.e. methods are cached, closed and friends are not)
477 file = self.__dict__['file']
478 a = getattr(file, name)
479 if hasattr(a, '__call__'):
480 func = a
481 @_functools.wraps(func)
482 def func_wrapper(*args, **kwargs):
483 return func(*args, **kwargs)
484 # Avoid closing the file as long as the wrapper is alive,
485 # see issue #18879.
486 func_wrapper._closer = self._closer
487 a = func_wrapper
488 if not isinstance(a, int):
489 setattr(self, name, a)
490 return a
491
492 # The underlying __enter__ method returns the wrong object
493 # (self.file) so override it to return the wrapper
494 def __enter__(self):
495 self.file.__enter__()
496 return self
497
498 # Need to trap __exit__ as well to ensure the file gets
499 # deleted when used in a with statement
500 def __exit__(self, exc, value, tb):
501 result = self.file.__exit__(exc, value, tb)
502 self.close()
503 return result
504
505 def close(self):
506 """
507 Close the temporary file, possibly deleting it.
508 """
509 self._closer.close()
510
511 # iter() doesn't use __getattr__ to find the __iter__ method
512 def __iter__(self):
Serhiy Storchakad83b7c22015-03-20 16:11:20 +0200513 # Don't return iter(self.file), but yield from it to avoid closing
R David Murray75ed90a2015-03-22 12:33:46 -0400514 # file as long as it's being used as iterator (see issue #23700). We
515 # can't use 'yield from' here because iter(file) returns the file
516 # object itself, which has a close method, and thus the file would get
517 # closed when the generator is finalized, due to PEP380 semantics.
Serhiy Storchakad83b7c22015-03-20 16:11:20 +0200518 for line in self.file:
519 yield line
Christian Heimes3ecfea712008-02-09 20:51:34 +0000520
521
Guido van Rossumf0c74162007-08-28 03:29:45 +0000522def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None,
Gregory P. Smithad577b92015-05-22 16:18:14 -0700523 newline=None, suffix=None, prefix=None,
sth825aab92018-05-23 07:07:01 +0200524 dir=None, delete=True, *, errors=None):
Guido van Rossum0e548712002-08-09 16:14:33 +0000525 """Create and return a temporary file.
526 Arguments:
527 'prefix', 'suffix', 'dir' -- as for mkstemp.
Guido van Rossumf0c74162007-08-28 03:29:45 +0000528 'mode' -- the mode argument to io.open (default "w+b").
529 'buffering' -- the buffer size argument to io.open (default -1).
530 'encoding' -- the encoding argument to io.open (default None)
531 'newline' -- the newline argument to io.open (default None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000532 'delete' -- whether the file is deleted on close (default True).
sth825aab92018-05-23 07:07:01 +0200533 'errors' -- the errors argument to io.open (default None)
Guido van Rossum0e548712002-08-09 16:14:33 +0000534 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000535
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000536 Returns an object with a file-like interface; the name of the file
Martin Panter1f0e1f32016-02-22 10:10:00 +0000537 is accessible as its 'name' attribute. The file will be automatically
538 deleted when it is closed unless the 'delete' argument is set to False.
Guido van Rossum0e548712002-08-09 16:14:33 +0000539 """
Tim Peters1baa22a2001-01-12 10:02:46 +0000540
Gregory P. Smithad577b92015-05-22 16:18:14 -0700541 prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
Guido van Rossume888cdc2002-08-17 14:50:24 +0000542
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000543 flags = _bin_openflags
Tim Peters1baa22a2001-01-12 10:02:46 +0000544
Guido van Rossum0e548712002-08-09 16:14:33 +0000545 # Setting O_TEMPORARY in the flags causes the OS to delete
546 # the file when it is closed. This is only supported by Windows.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000547 if _os.name == 'nt' and delete:
Guido van Rossum0e548712002-08-09 16:14:33 +0000548 flags |= _os.O_TEMPORARY
Tim Peters1baa22a2001-01-12 10:02:46 +0000549
Inada Naoki48274832021-03-29 12:28:14 +0900550 if "b" not in mode:
551 encoding = _io.text_encoding(encoding)
552
Gregory P. Smithad577b92015-05-22 16:18:14 -0700553 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type)
Victor Stinner1f99f9d2014-03-25 09:18:04 +0100554 try:
555 file = _io.open(fd, mode, buffering=buffering,
sth825aab92018-05-23 07:07:01 +0200556 newline=newline, encoding=encoding, errors=errors)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000557
Victor Stinner1f99f9d2014-03-25 09:18:04 +0100558 return _TemporaryFileWrapper(file, name, delete)
Martin Panter7869a222016-02-28 05:22:20 +0000559 except BaseException:
560 _os.unlink(name)
Victor Stinner1f99f9d2014-03-25 09:18:04 +0100561 _os.close(fd)
562 raise
Guido van Rossum0e548712002-08-09 16:14:33 +0000563
Steve Dower60419a72019-06-24 08:42:54 -0700564if _os.name != 'posix' or _sys.platform == 'cygwin':
Jason Tishler80c02af2002-08-14 15:10:09 +0000565 # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
566 # while it is open.
Guido van Rossum0e548712002-08-09 16:14:33 +0000567 TemporaryFile = NamedTemporaryFile
Tim Peters1baa22a2001-01-12 10:02:46 +0000568
569else:
Victor Stinnerd967fc92014-06-05 14:27:45 +0200570 # Is the O_TMPFILE flag available and does it work?
571 # The flag is set to False if os.open(dir, os.O_TMPFILE) raises an
572 # IsADirectoryError exception
573 _O_TMPFILE_WORKS = hasattr(_os, 'O_TMPFILE')
574
Guido van Rossumf0c74162007-08-28 03:29:45 +0000575 def TemporaryFile(mode='w+b', buffering=-1, encoding=None,
Gregory P. Smithad577b92015-05-22 16:18:14 -0700576 newline=None, suffix=None, prefix=None,
sth825aab92018-05-23 07:07:01 +0200577 dir=None, *, errors=None):
Guido van Rossum0e548712002-08-09 16:14:33 +0000578 """Create and return a temporary file.
579 Arguments:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000580 'prefix', 'suffix', 'dir' -- as for mkstemp.
Guido van Rossumf0c74162007-08-28 03:29:45 +0000581 'mode' -- the mode argument to io.open (default "w+b").
582 'buffering' -- the buffer size argument to io.open (default -1).
583 'encoding' -- the encoding argument to io.open (default None)
584 'newline' -- the newline argument to io.open (default None)
sth825aab92018-05-23 07:07:01 +0200585 'errors' -- the errors argument to io.open (default None)
Guido van Rossum0e548712002-08-09 16:14:33 +0000586 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000587
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000588 Returns an object with a file-like interface. The file has no
589 name, and will cease to exist when it is closed.
Guido van Rossum0e548712002-08-09 16:14:33 +0000590 """
Victor Stinnerd967fc92014-06-05 14:27:45 +0200591 global _O_TMPFILE_WORKS
Guido van Rossum0e548712002-08-09 16:14:33 +0000592
Inada Naoki48274832021-03-29 12:28:14 +0900593 if "b" not in mode:
594 encoding = _io.text_encoding(encoding)
595
Gregory P. Smithad577b92015-05-22 16:18:14 -0700596 prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
Guido van Rossume888cdc2002-08-17 14:50:24 +0000597
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000598 flags = _bin_openflags
Victor Stinnerd967fc92014-06-05 14:27:45 +0200599 if _O_TMPFILE_WORKS:
600 try:
601 flags2 = (flags | _os.O_TMPFILE) & ~_os.O_CREAT
602 fd = _os.open(dir, flags2, 0o600)
603 except IsADirectoryError:
Victor Stinner9aba8c82015-10-21 00:15:08 +0200604 # Linux kernel older than 3.11 ignores the O_TMPFILE flag:
605 # O_TMPFILE is read as O_DIRECTORY. Trying to open a directory
606 # with O_RDWR|O_DIRECTORY fails with IsADirectoryError, a
607 # directory cannot be open to write. Set flag to False to not
608 # try again.
Victor Stinnerd967fc92014-06-05 14:27:45 +0200609 _O_TMPFILE_WORKS = False
610 except OSError:
611 # The filesystem of the directory does not support O_TMPFILE.
612 # For example, OSError(95, 'Operation not supported').
Victor Stinner9aba8c82015-10-21 00:15:08 +0200613 #
614 # On Linux kernel older than 3.11, trying to open a regular
615 # file (or a symbolic link to a regular file) with O_TMPFILE
616 # fails with NotADirectoryError, because O_TMPFILE is read as
617 # O_DIRECTORY.
Victor Stinnerd967fc92014-06-05 14:27:45 +0200618 pass
619 else:
620 try:
621 return _io.open(fd, mode, buffering=buffering,
sth825aab92018-05-23 07:07:01 +0200622 newline=newline, encoding=encoding,
623 errors=errors)
Victor Stinnerd967fc92014-06-05 14:27:45 +0200624 except:
625 _os.close(fd)
626 raise
627 # Fallback to _mkstemp_inner().
Guido van Rossum0e548712002-08-09 16:14:33 +0000628
Gregory P. Smithad577b92015-05-22 16:18:14 -0700629 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type)
Guido van Rossum0e548712002-08-09 16:14:33 +0000630 try:
631 _os.unlink(name)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000632 return _io.open(fd, mode, buffering=buffering,
sth825aab92018-05-23 07:07:01 +0200633 newline=newline, encoding=encoding, errors=errors)
Guido van Rossum0e548712002-08-09 16:14:33 +0000634 except:
635 _os.close(fd)
636 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +0000637
638class SpooledTemporaryFile:
Serhiy Storchaka4f169a72013-02-09 11:46:42 +0200639 """Temporary file wrapper, specialized to switch from BytesIO
640 or StringIO to a real file when it exceeds a certain size or
Guido van Rossumd8faa362007-04-27 19:54:29 +0000641 when a fileno is needed.
642 """
643 _rolled = False
644
Guido van Rossumf0c74162007-08-28 03:29:45 +0000645 def __init__(self, max_size=0, mode='w+b', buffering=-1,
646 encoding=None, newline=None,
sth825aab92018-05-23 07:07:01 +0200647 suffix=None, prefix=None, dir=None, *, errors=None):
Guido van Rossum9a634702007-07-09 10:24:45 +0000648 if 'b' in mode:
649 self._file = _io.BytesIO()
650 else:
Inada Naoki48274832021-03-29 12:28:14 +0900651 encoding = _io.text_encoding(encoding)
Inada Naokiea9835c2019-11-27 22:22:06 +0900652 self._file = _io.TextIOWrapper(_io.BytesIO(),
653 encoding=encoding, errors=errors,
654 newline=newline)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000655 self._max_size = max_size
656 self._rolled = False
Guido van Rossumf0c74162007-08-28 03:29:45 +0000657 self._TemporaryFileArgs = {'mode': mode, 'buffering': buffering,
658 'suffix': suffix, 'prefix': prefix,
659 'encoding': encoding, 'newline': newline,
sth825aab92018-05-23 07:07:01 +0200660 'dir': dir, 'errors': errors}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000661
Guido van Rossum48b069a2020-04-07 09:50:06 -0700662 __class_getitem__ = classmethod(_types.GenericAlias)
Batuhan Taşkaya09c482f2019-12-30 19:08:08 +0300663
Guido van Rossumd8faa362007-04-27 19:54:29 +0000664 def _check(self, file):
665 if self._rolled: return
666 max_size = self._max_size
667 if max_size and file.tell() > max_size:
668 self.rollover()
669
670 def rollover(self):
671 if self._rolled: return
672 file = self._file
Guido van Rossumf0c74162007-08-28 03:29:45 +0000673 newfile = self._file = TemporaryFile(**self._TemporaryFileArgs)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000674 del self._TemporaryFileArgs
675
Inada Naokiea9835c2019-11-27 22:22:06 +0900676 pos = file.tell()
677 if hasattr(newfile, 'buffer'):
678 newfile.buffer.write(file.detach().getvalue())
679 else:
680 newfile.write(file.getvalue())
681 newfile.seek(pos, 0)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000682
683 self._rolled = True
684
Christian Heimes3ecfea712008-02-09 20:51:34 +0000685 # The method caching trick from NamedTemporaryFile
686 # won't work here, because _file may change from a
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300687 # BytesIO/StringIO instance to a real file. So we list
Christian Heimes3ecfea712008-02-09 20:51:34 +0000688 # all the methods directly.
689
690 # Context management protocol
691 def __enter__(self):
692 if self._file.closed:
693 raise ValueError("Cannot enter context with closed file")
694 return self
695
696 def __exit__(self, exc, value, tb):
697 self._file.close()
698
Guido van Rossumd8faa362007-04-27 19:54:29 +0000699 # file protocol
700 def __iter__(self):
701 return self._file.__iter__()
702
703 def close(self):
704 self._file.close()
705
706 @property
707 def closed(self):
708 return self._file.closed
709
710 @property
711 def encoding(self):
sth825aab92018-05-23 07:07:01 +0200712 return self._file.encoding
713
714 @property
715 def errors(self):
716 return self._file.errors
Guido van Rossumd8faa362007-04-27 19:54:29 +0000717
718 def fileno(self):
719 self.rollover()
720 return self._file.fileno()
721
722 def flush(self):
723 self._file.flush()
724
725 def isatty(self):
726 return self._file.isatty()
727
728 @property
729 def mode(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200730 try:
731 return self._file.mode
732 except AttributeError:
733 return self._TemporaryFileArgs['mode']
Guido van Rossumd8faa362007-04-27 19:54:29 +0000734
735 @property
736 def name(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200737 try:
738 return self._file.name
739 except AttributeError:
740 return None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000741
742 @property
743 def newlines(self):
sth825aab92018-05-23 07:07:01 +0200744 return self._file.newlines
Guido van Rossumd8faa362007-04-27 19:54:29 +0000745
746 def read(self, *args):
747 return self._file.read(*args)
748
749 def readline(self, *args):
750 return self._file.readline(*args)
751
752 def readlines(self, *args):
753 return self._file.readlines(*args)
754
755 def seek(self, *args):
Inada Naoki485e7152020-04-17 15:56:35 +0900756 return self._file.seek(*args)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000757
Guido van Rossumd8faa362007-04-27 19:54:29 +0000758 def tell(self):
759 return self._file.tell()
760
Antoine Pitrou0e86a582011-11-25 18:03:09 +0100761 def truncate(self, size=None):
762 if size is None:
763 self._file.truncate()
764 else:
765 if size > self._max_size:
766 self.rollover()
767 self._file.truncate(size)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000768
769 def write(self, s):
770 file = self._file
771 rv = file.write(s)
772 self._check(file)
773 return rv
774
775 def writelines(self, iterable):
776 file = self._file
777 rv = file.writelines(iterable)
778 self._check(file)
779 return rv
780
Nick Coghlan543af752010-10-24 11:23:25 +0000781
CAM Gerlachbd2fa3c2021-03-14 13:06:56 -0500782class TemporaryDirectory:
Nick Coghlan543af752010-10-24 11:23:25 +0000783 """Create and return a temporary directory. This has the same
784 behavior as mkdtemp but can be used as a context manager. For
785 example:
786
787 with TemporaryDirectory() as tmpdir:
788 ...
789
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300790 Upon exiting the context, the directory and everything contained
Nick Coghlan543af752010-10-24 11:23:25 +0000791 in it are removed.
792 """
793
CAM Gerlachbd2fa3c2021-03-14 13:06:56 -0500794 def __init__(self, suffix=None, prefix=None, dir=None,
795 ignore_cleanup_errors=False):
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000796 self.name = mkdtemp(suffix, prefix, dir)
CAM Gerlachbd2fa3c2021-03-14 13:06:56 -0500797 self._ignore_cleanup_errors = ignore_cleanup_errors
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200798 self._finalizer = _weakref.finalize(
799 self, self._cleanup, self.name,
CAM Gerlachbd2fa3c2021-03-14 13:06:56 -0500800 warn_message="Implicitly cleaning up {!r}".format(self),
801 ignore_errors=self._ignore_cleanup_errors)
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200802
803 @classmethod
CAM Gerlachbd2fa3c2021-03-14 13:06:56 -0500804 def _rmtree(cls, name, ignore_errors=False):
Serhiy Storchakae9b51c02019-05-31 11:30:37 +0300805 def onerror(func, path, exc_info):
806 if issubclass(exc_info[0], PermissionError):
807 def resetperms(path):
808 try:
809 _os.chflags(path, 0)
810 except AttributeError:
811 pass
812 _os.chmod(path, 0o700)
813
814 try:
815 if path != name:
816 resetperms(_os.path.dirname(path))
817 resetperms(path)
818
819 try:
820 _os.unlink(path)
821 # PermissionError is raised on FreeBSD for directories
822 except (IsADirectoryError, PermissionError):
CAM Gerlachbd2fa3c2021-03-14 13:06:56 -0500823 cls._rmtree(path, ignore_errors=ignore_errors)
Serhiy Storchakae9b51c02019-05-31 11:30:37 +0300824 except FileNotFoundError:
825 pass
826 elif issubclass(exc_info[0], FileNotFoundError):
827 pass
828 else:
CAM Gerlachbd2fa3c2021-03-14 13:06:56 -0500829 if not ignore_errors:
830 raise
Serhiy Storchakae9b51c02019-05-31 11:30:37 +0300831
832 _shutil.rmtree(name, onerror=onerror)
833
834 @classmethod
CAM Gerlachbd2fa3c2021-03-14 13:06:56 -0500835 def _cleanup(cls, name, warn_message, ignore_errors=False):
836 cls._rmtree(name, ignore_errors=ignore_errors)
Serhiy Storchaka5e193ac2014-09-24 13:26:25 +0300837 _warnings.warn(warn_message, ResourceWarning)
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200838
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000839 def __repr__(self):
840 return "<{} {!r}>".format(self.__class__.__name__, self.name)
Nick Coghlan543af752010-10-24 11:23:25 +0000841
842 def __enter__(self):
843 return self.name
844
Nick Coghlan543af752010-10-24 11:23:25 +0000845 def __exit__(self, exc, value, tb):
846 self.cleanup()
847
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200848 def cleanup(self):
CAM Gerlachbd2fa3c2021-03-14 13:06:56 -0500849 if self._finalizer.detach() or _os.path.exists(self.name):
850 self._rmtree(self.name, ignore_errors=self._ignore_cleanup_errors)
Batuhan Taşkaya03615562020-04-10 17:46:36 +0300851
852 __class_getitem__ = classmethod(_types.GenericAlias)