blob: efcf7a7fb3bbc1968d56a911c752d7b0e3d7fc86 [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
91 if isinstance(arg, bytes):
92 if return_type is str:
93 raise TypeError("Can't mix bytes and non-bytes in "
94 "path components.")
95 return_type = bytes
96 else:
97 if return_type is bytes:
98 raise TypeError("Can't mix bytes and non-bytes in "
99 "path components.")
100 return_type = str
101 if return_type is None:
Eric L9c792742021-03-03 21:36:22 +0100102 if tempdir is None or isinstance(tempdir, str):
103 return str # tempfile APIs return a str by default.
104 else:
105 # we could check for bytes but it'll fail later on anyway
106 return bytes
Gregory P. Smithad577b92015-05-22 16:18:14 -0700107 return return_type
108
109
110def _sanitize_params(prefix, suffix, dir):
111 """Common parameter processing for most APIs in this module."""
112 output_type = _infer_return_type(prefix, suffix, dir)
113 if suffix is None:
114 suffix = output_type()
115 if prefix is None:
116 if output_type is str:
117 prefix = template
118 else:
119 prefix = _os.fsencode(template)
120 if dir is None:
121 if output_type is str:
122 dir = gettempdir()
123 else:
124 dir = gettempdirb()
125 return prefix, suffix, dir, output_type
126
127
Victor Stinner1e62bf12017-04-19 22:59:51 +0200128class _RandomNameSequence:
129 """An instance of _RandomNameSequence generates an endless
130 sequence of unpredictable strings which can safely be incorporated
Wolfgang Maier9c463ec2018-04-09 02:42:39 +0200131 into file names. Each string is eight characters long. Multiple
Victor Stinner1e62bf12017-04-19 22:59:51 +0200132 threads can safely use the same instance at the same time.
133
134 _RandomNameSequence is an iterator."""
Guido van Rossum0e548712002-08-09 16:14:33 +0000135
Inada Naoki43ca0842020-10-31 11:15:38 +0900136 characters = "abcdefghijklmnopqrstuvwxyz0123456789_"
137
138 @property
139 def rng(self):
140 cur_pid = _os.getpid()
141 if cur_pid != getattr(self, '_rng_pid', None):
142 self._rng = _Random()
143 self._rng_pid = cur_pid
144 return self._rng
Victor Stinner1e62bf12017-04-19 22:59:51 +0200145
146 def __iter__(self):
147 return self
148
149 def __next__(self):
Inada Naokid2810052020-11-01 20:02:03 +0900150 return ''.join(self.rng.choices(self.characters, k=8))
Guido van Rossum0e548712002-08-09 16:14:33 +0000151
152def _candidate_tempdir_list():
153 """Generate a list of candidate temporary directories which
154 _get_default_tempdir will try."""
155
156 dirlist = []
157
158 # First, try the environment.
159 for envname in 'TMPDIR', 'TEMP', 'TMP':
160 dirname = _os.getenv(envname)
161 if dirname: dirlist.append(dirname)
162
163 # Failing that, try OS-specific locations.
Alexandre Vassalottieca20b62008-05-16 02:54:33 +0000164 if _os.name == 'nt':
Steve Dowere5f41d22018-05-16 17:50:29 -0400165 dirlist.extend([ _os.path.expanduser(r'~\AppData\Local\Temp'),
166 _os.path.expandvars(r'%SYSTEMROOT%\Temp'),
167 r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
Guido van Rossum0e548712002-08-09 16:14:33 +0000168 else:
169 dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
170
171 # As a last resort, the current directory.
172 try:
173 dirlist.append(_os.getcwd())
Florent Xicluna68f71a32011-10-28 16:06:23 +0200174 except (AttributeError, OSError):
Guido van Rossum0e548712002-08-09 16:14:33 +0000175 dirlist.append(_os.curdir)
176
177 return dirlist
Tim Petersa0d55de2002-08-09 18:01:01 +0000178
Guido van Rossum0e548712002-08-09 16:14:33 +0000179def _get_default_tempdir():
180 """Calculate the default directory to use for temporary files.
Guido van Rossume888cdc2002-08-17 14:50:24 +0000181 This routine should be called exactly once.
Guido van Rossum0e548712002-08-09 16:14:33 +0000182
183 We determine whether or not a candidate temp dir is usable by
184 trying to create and write to a file in that directory. If this
185 is successful, the test file is deleted. To prevent denial of
186 service, the name of the test file must be randomized."""
187
188 namer = _RandomNameSequence()
189 dirlist = _candidate_tempdir_list()
Guido van Rossum0e548712002-08-09 16:14:33 +0000190
191 for dir in dirlist:
192 if dir != _os.curdir:
Tim Golden6d09f092013-10-25 18:38:16 +0100193 dir = _os.path.abspath(dir)
Guido van Rossum0e548712002-08-09 16:14:33 +0000194 # Try only a few names per directory.
Guido van Rossum805365e2007-05-07 22:24:25 +0000195 for seq in range(100):
Georg Brandla18af4e2007-04-21 15:47:16 +0000196 name = next(namer)
Guido van Rossum0e548712002-08-09 16:14:33 +0000197 filename = _os.path.join(dir, name)
198 try:
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000199 fd = _os.open(filename, _bin_openflags, 0o600)
Serhiy Storchakaf6b361e2013-02-13 00:35:30 +0200200 try:
201 try:
Serhiy Storchaka76a2ed12013-02-13 00:59:26 +0200202 with _io.open(fd, 'wb', closefd=False) as fp:
203 fp.write(b'blat')
Serhiy Storchakaf6b361e2013-02-13 00:35:30 +0200204 finally:
205 _os.close(fd)
206 finally:
207 _os.unlink(filename)
Guido van Rossum0e548712002-08-09 16:14:33 +0000208 return dir
Florent Xicluna68f71a32011-10-28 16:06:23 +0200209 except FileExistsError:
Guido van Rossum0e548712002-08-09 16:14:33 +0000210 pass
Serhiy Storchaka5d6b7b12015-05-20 00:11:48 +0300211 except PermissionError:
212 # This exception is thrown when a directory with the chosen name
213 # already exists on windows.
214 if (_os.name == 'nt' and _os.path.isdir(dir) and
215 _os.access(dir, _os.W_OK)):
216 continue
217 break # no point trying more names in this directory
Florent Xicluna68f71a32011-10-28 16:06:23 +0200218 except OSError:
219 break # no point trying more names in this directory
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200220 raise FileNotFoundError(_errno.ENOENT,
221 "No usable temporary directory found in %s" %
222 dirlist)
Guido van Rossum0e548712002-08-09 16:14:33 +0000223
Guido van Rossume888cdc2002-08-17 14:50:24 +0000224_name_sequence = None
225
Guido van Rossum0e548712002-08-09 16:14:33 +0000226def _get_candidate_names():
227 """Common setup sequence for all user-callable interfaces."""
228
Guido van Rossume888cdc2002-08-17 14:50:24 +0000229 global _name_sequence
230 if _name_sequence is None:
231 _once_lock.acquire()
232 try:
233 if _name_sequence is None:
234 _name_sequence = _RandomNameSequence()
235 finally:
236 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000237 return _name_sequence
Guido van Rossum41f95031992-03-31 19:02:01 +0000238
239
Gregory P. Smithad577b92015-05-22 16:18:14 -0700240def _mkstemp_inner(dir, pre, suf, flags, output_type):
Guido van Rossum0e548712002-08-09 16:14:33 +0000241 """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
Tim Peters9fadfb02001-01-13 03:04:02 +0000242
Guido van Rossum0e548712002-08-09 16:14:33 +0000243 names = _get_candidate_names()
Gregory P. Smithad577b92015-05-22 16:18:14 -0700244 if output_type is bytes:
245 names = map(_os.fsencode, names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000246
Guido van Rossum805365e2007-05-07 22:24:25 +0000247 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000248 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000249 file = _os.path.join(dir, pre + name + suf)
Steve Dower60419a72019-06-24 08:42:54 -0700250 _sys.audit("tempfile.mkstemp", file)
Guido van Rossum0e548712002-08-09 16:14:33 +0000251 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000252 fd = _os.open(file, flags, 0o600)
Florent Xicluna68f71a32011-10-28 16:06:23 +0200253 except FileExistsError:
254 continue # try again
Eli Benderskyf315df32013-09-06 06:11:19 -0700255 except PermissionError:
256 # This exception is thrown when a directory with the chosen name
257 # already exists on windows.
Serhiy Storchaka5d6b7b12015-05-20 00:11:48 +0300258 if (_os.name == 'nt' and _os.path.isdir(dir) and
259 _os.access(dir, _os.W_OK)):
Eli Benderskyf315df32013-09-06 06:11:19 -0700260 continue
261 else:
262 raise
Gregory P. Smithad577b92015-05-22 16:18:14 -0700263 return (fd, _os.path.abspath(file))
Guido van Rossum0e548712002-08-09 16:14:33 +0000264
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200265 raise FileExistsError(_errno.EEXIST,
266 "No usable temporary file name found")
Tim Petersa0d55de2002-08-09 18:01:01 +0000267
Guido van Rossum0e548712002-08-09 16:14:33 +0000268
269# User visible interfaces.
Guido van Rossumb0e57181998-10-14 20:27:05 +0000270
Guido van Rossum41f95031992-03-31 19:02:01 +0000271def gettempprefix():
Eric L9c792742021-03-03 21:36:22 +0100272 """The default prefix for temporary directories as string."""
273 return _os.fsdecode(template)
Tim Peters9fadfb02001-01-13 03:04:02 +0000274
Gregory P. Smithad577b92015-05-22 16:18:14 -0700275def gettempprefixb():
276 """The default prefix for temporary directories as bytes."""
Eric L9c792742021-03-03 21:36:22 +0100277 return _os.fsencode(template)
Gregory P. Smithad577b92015-05-22 16:18:14 -0700278
Guido van Rossume888cdc2002-08-17 14:50:24 +0000279tempdir = None
280
Eric L9c792742021-03-03 21:36:22 +0100281def _gettempdir():
282 """Private accessor for tempfile.tempdir."""
Guido van Rossume888cdc2002-08-17 14:50:24 +0000283 global tempdir
284 if tempdir is None:
285 _once_lock.acquire()
286 try:
287 if tempdir is None:
288 tempdir = _get_default_tempdir()
289 finally:
290 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000291 return tempdir
292
Eric L9c792742021-03-03 21:36:22 +0100293def gettempdir():
294 """Returns tempfile.tempdir as str."""
295 return _os.fsdecode(_gettempdir())
296
Gregory P. Smithad577b92015-05-22 16:18:14 -0700297def gettempdirb():
Eric L9c792742021-03-03 21:36:22 +0100298 """Returns tempfile.tempdir as bytes."""
299 return _os.fsencode(_gettempdir())
Gregory P. Smithad577b92015-05-22 16:18:14 -0700300
301def mkstemp(suffix=None, prefix=None, dir=None, text=False):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000302 """User-callable function to create and return a unique temporary
Guido van Rossum0e548712002-08-09 16:14:33 +0000303 file. The return value is a pair (fd, name) where fd is the
304 file descriptor returned by os.open, and name is the filename.
305
Martin Panter9b566c32015-11-07 00:32:50 +0000306 If 'suffix' is not None, the file name will end with that suffix,
Guido van Rossum0e548712002-08-09 16:14:33 +0000307 otherwise there will be no suffix.
308
Martin Panter9b566c32015-11-07 00:32:50 +0000309 If 'prefix' is not None, the file name will begin with that prefix,
Guido van Rossum0e548712002-08-09 16:14:33 +0000310 otherwise a default prefix is used.
311
Martin Panter9b566c32015-11-07 00:32:50 +0000312 If 'dir' is not None, the file will be created in that directory,
Guido van Rossum0e548712002-08-09 16:14:33 +0000313 otherwise a default directory is used.
314
Tim Peters04490bf2002-08-14 15:41:26 +0000315 If 'text' is specified and true, the file is opened in text
Rishav Kundue55de682020-08-14 07:03:14 +0530316 mode. Else (the default) the file is opened in binary mode.
Guido van Rossum0e548712002-08-09 16:14:33 +0000317
Martin Panter9b566c32015-11-07 00:32:50 +0000318 If any of 'suffix', 'prefix' and 'dir' are not None, they must be the
319 same type. If they are bytes, the returned name will be bytes; str
320 otherwise.
Gregory P. Smithad577b92015-05-22 16:18:14 -0700321
Guido van Rossum0e548712002-08-09 16:14:33 +0000322 The file is readable and writable only by the creating user ID.
323 If the operating system uses permission bits to indicate whether a
324 file is executable, the file is executable by no one. The file
325 descriptor is not inherited by children of this process.
326
327 Caller is responsible for deleting the file when done with it.
Tim Peters9fadfb02001-01-13 03:04:02 +0000328 """
329
Gregory P. Smithad577b92015-05-22 16:18:14 -0700330 prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
Guido van Rossume888cdc2002-08-17 14:50:24 +0000331
Tim Peters04490bf2002-08-14 15:41:26 +0000332 if text:
Guido van Rossum0e548712002-08-09 16:14:33 +0000333 flags = _text_openflags
Tim Peters04490bf2002-08-14 15:41:26 +0000334 else:
335 flags = _bin_openflags
Guido van Rossum0e548712002-08-09 16:14:33 +0000336
Gregory P. Smithad577b92015-05-22 16:18:14 -0700337 return _mkstemp_inner(dir, prefix, suffix, flags, output_type)
Guido van Rossumcff34541992-01-14 18:31:56 +0000338
Guido van Rossumeee94981991-11-12 15:38:08 +0000339
Gregory P. Smithad577b92015-05-22 16:18:14 -0700340def mkdtemp(suffix=None, prefix=None, dir=None):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000341 """User-callable function to create and return a unique temporary
Guido van Rossum0e548712002-08-09 16:14:33 +0000342 directory. The return value is the pathname of the directory.
343
Tim Peters04490bf2002-08-14 15:41:26 +0000344 Arguments are as for mkstemp, except that the 'text' argument is
Guido van Rossum0e548712002-08-09 16:14:33 +0000345 not accepted.
346
347 The directory is readable, writable, and searchable only by the
348 creating user.
349
350 Caller is responsible for deleting the directory when done with it.
351 """
352
Gregory P. Smithad577b92015-05-22 16:18:14 -0700353 prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
Guido van Rossume888cdc2002-08-17 14:50:24 +0000354
Guido van Rossum0e548712002-08-09 16:14:33 +0000355 names = _get_candidate_names()
Gregory P. Smithad577b92015-05-22 16:18:14 -0700356 if output_type is bytes:
357 names = map(_os.fsencode, names)
Tim Petersa0d55de2002-08-09 18:01:01 +0000358
Guido van Rossum805365e2007-05-07 22:24:25 +0000359 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000360 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000361 file = _os.path.join(dir, prefix + name + suffix)
Steve Dower60419a72019-06-24 08:42:54 -0700362 _sys.audit("tempfile.mkdtemp", file)
Guido van Rossum0e548712002-08-09 16:14:33 +0000363 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000364 _os.mkdir(file, 0o700)
Florent Xicluna68f71a32011-10-28 16:06:23 +0200365 except FileExistsError:
366 continue # try again
Serhiy Storchaka5d6b7b12015-05-20 00:11:48 +0300367 except PermissionError:
368 # This exception is thrown when a directory with the chosen name
369 # already exists on windows.
370 if (_os.name == 'nt' and _os.path.isdir(dir) and
371 _os.access(dir, _os.W_OK)):
372 continue
373 else:
374 raise
Gregory P. Smithad577b92015-05-22 16:18:14 -0700375 return file
Guido van Rossum0e548712002-08-09 16:14:33 +0000376
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200377 raise FileExistsError(_errno.EEXIST,
378 "No usable temporary directory name found")
Guido van Rossum0e548712002-08-09 16:14:33 +0000379
Guido van Rossume888cdc2002-08-17 14:50:24 +0000380def mktemp(suffix="", prefix=template, dir=None):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000381 """User-callable function to return a unique temporary file name. The
Guido van Rossum0e548712002-08-09 16:14:33 +0000382 file is not created.
383
Martin Panter9b566c32015-11-07 00:32:50 +0000384 Arguments are similar to mkstemp, except that the 'text' argument is
385 not accepted, and suffix=None, prefix=None and bytes file names are not
386 supported.
Guido van Rossum0e548712002-08-09 16:14:33 +0000387
Gregory P. Smithad577b92015-05-22 16:18:14 -0700388 THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may
389 refer to a file that did not exist at some point, but by the time
Guido van Rossum0e548712002-08-09 16:14:33 +0000390 you get around to creating it, someone else may have beaten you to
391 the punch.
392 """
393
Guido van Rossum44f602d2002-11-22 15:56:29 +0000394## from warnings import warn as _warn
395## _warn("mktemp is a potential security risk to your program",
396## RuntimeWarning, stacklevel=2)
Guido van Rossum0e548712002-08-09 16:14:33 +0000397
Guido van Rossume888cdc2002-08-17 14:50:24 +0000398 if dir is None:
399 dir = gettempdir()
400
Guido van Rossum0e548712002-08-09 16:14:33 +0000401 names = _get_candidate_names()
Guido van Rossum805365e2007-05-07 22:24:25 +0000402 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000403 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000404 file = _os.path.join(dir, prefix + name + suffix)
Guido van Rossumb256159392003-11-10 02:16:36 +0000405 if not _exists(file):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000406 return file
Guido van Rossumca549821997-08-12 18:00:12 +0000407
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200408 raise FileExistsError(_errno.EEXIST,
409 "No usable temporary filename found")
Guido van Rossumca549821997-08-12 18:00:12 +0000410
Christian Heimes3ecfea712008-02-09 20:51:34 +0000411
Antoine Pitrou17c93262013-12-21 22:14:56 +0100412class _TemporaryFileCloser:
413 """A separate object allowing proper closing of a temporary file's
414 underlying file object, without adding a __del__ method to the
415 temporary file."""
Tim Petersa255a722001-12-18 22:32:40 +0000416
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200417 file = None # Set here since __del__ checks it
Serhiy Storchaka99e033b2014-01-27 11:18:27 +0200418 close_called = False
419
Guido van Rossumd8faa362007-04-27 19:54:29 +0000420 def __init__(self, file, name, delete=True):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000421 self.file = file
Guido van Rossum0e548712002-08-09 16:14:33 +0000422 self.name = name
Guido van Rossumd8faa362007-04-27 19:54:29 +0000423 self.delete = delete
Guido van Rossumca549821997-08-12 18:00:12 +0000424
Guido van Rossum0e548712002-08-09 16:14:33 +0000425 # NT provides delete-on-close as a primitive, so we don't need
426 # the wrapper to do anything special. We still use it so that
427 # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
428 if _os.name != 'nt':
Guido van Rossum0e548712002-08-09 16:14:33 +0000429 # Cache the unlinker so we don't get spurious errors at
430 # shutdown when the module-level "os" is None'd out. Note
431 # that this must be referenced as self.unlink, because the
432 # name TemporaryFileWrapper may also get None'd out before
433 # __del__ is called.
Tim Peters1baa22a2001-01-12 10:02:46 +0000434
Serhiy Storchaka99e033b2014-01-27 11:18:27 +0200435 def close(self, unlink=_os.unlink):
436 if not self.close_called and self.file is not None:
Tim Peters6ef966e2002-11-21 15:48:33 +0000437 self.close_called = True
Serhiy Storchaka7e7a3db2015-04-10 13:24:41 +0300438 try:
439 self.file.close()
440 finally:
441 if self.delete:
442 unlink(self.name)
Tim Peters1baa22a2001-01-12 10:02:46 +0000443
Antoine Pitrou17c93262013-12-21 22:14:56 +0100444 # Need to ensure the file is deleted on __del__
Guido van Rossum0e548712002-08-09 16:14:33 +0000445 def __del__(self):
446 self.close()
Tim Peters1baa22a2001-01-12 10:02:46 +0000447
Benjamin Peterson98d23f22009-06-30 22:27:25 +0000448 else:
Antoine Pitrou17c93262013-12-21 22:14:56 +0100449 def close(self):
450 if not self.close_called:
451 self.close_called = True
452 self.file.close()
453
454
455class _TemporaryFileWrapper:
456 """Temporary file wrapper
457
458 This class provides a wrapper around files opened for
459 temporary use. In particular, it seeks to automatically
460 remove the file when it is no longer needed.
461 """
462
463 def __init__(self, file, name, delete=True):
464 self.file = file
465 self.name = name
466 self.delete = delete
467 self._closer = _TemporaryFileCloser(file, name, delete)
468
469 def __getattr__(self, name):
470 # Attribute lookups are delegated to the underlying file
471 # and cached for non-numeric results
472 # (i.e. methods are cached, closed and friends are not)
473 file = self.__dict__['file']
474 a = getattr(file, name)
475 if hasattr(a, '__call__'):
476 func = a
477 @_functools.wraps(func)
478 def func_wrapper(*args, **kwargs):
479 return func(*args, **kwargs)
480 # Avoid closing the file as long as the wrapper is alive,
481 # see issue #18879.
482 func_wrapper._closer = self._closer
483 a = func_wrapper
484 if not isinstance(a, int):
485 setattr(self, name, a)
486 return a
487
488 # The underlying __enter__ method returns the wrong object
489 # (self.file) so override it to return the wrapper
490 def __enter__(self):
491 self.file.__enter__()
492 return self
493
494 # Need to trap __exit__ as well to ensure the file gets
495 # deleted when used in a with statement
496 def __exit__(self, exc, value, tb):
497 result = self.file.__exit__(exc, value, tb)
498 self.close()
499 return result
500
501 def close(self):
502 """
503 Close the temporary file, possibly deleting it.
504 """
505 self._closer.close()
506
507 # iter() doesn't use __getattr__ to find the __iter__ method
508 def __iter__(self):
Serhiy Storchakad83b7c22015-03-20 16:11:20 +0200509 # Don't return iter(self.file), but yield from it to avoid closing
R David Murray75ed90a2015-03-22 12:33:46 -0400510 # file as long as it's being used as iterator (see issue #23700). We
511 # can't use 'yield from' here because iter(file) returns the file
512 # object itself, which has a close method, and thus the file would get
513 # closed when the generator is finalized, due to PEP380 semantics.
Serhiy Storchakad83b7c22015-03-20 16:11:20 +0200514 for line in self.file:
515 yield line
Christian Heimes3ecfea712008-02-09 20:51:34 +0000516
517
Guido van Rossumf0c74162007-08-28 03:29:45 +0000518def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None,
Gregory P. Smithad577b92015-05-22 16:18:14 -0700519 newline=None, suffix=None, prefix=None,
sth825aab92018-05-23 07:07:01 +0200520 dir=None, delete=True, *, errors=None):
Guido van Rossum0e548712002-08-09 16:14:33 +0000521 """Create and return a temporary file.
522 Arguments:
523 'prefix', 'suffix', 'dir' -- as for mkstemp.
Guido van Rossumf0c74162007-08-28 03:29:45 +0000524 'mode' -- the mode argument to io.open (default "w+b").
525 'buffering' -- the buffer size argument to io.open (default -1).
526 'encoding' -- the encoding argument to io.open (default None)
527 'newline' -- the newline argument to io.open (default None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000528 'delete' -- whether the file is deleted on close (default True).
sth825aab92018-05-23 07:07:01 +0200529 'errors' -- the errors argument to io.open (default None)
Guido van Rossum0e548712002-08-09 16:14:33 +0000530 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000531
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000532 Returns an object with a file-like interface; the name of the file
Martin Panter1f0e1f32016-02-22 10:10:00 +0000533 is accessible as its 'name' attribute. The file will be automatically
534 deleted when it is closed unless the 'delete' argument is set to False.
Guido van Rossum0e548712002-08-09 16:14:33 +0000535 """
Tim Peters1baa22a2001-01-12 10:02:46 +0000536
Gregory P. Smithad577b92015-05-22 16:18:14 -0700537 prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
Guido van Rossume888cdc2002-08-17 14:50:24 +0000538
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000539 flags = _bin_openflags
Tim Peters1baa22a2001-01-12 10:02:46 +0000540
Guido van Rossum0e548712002-08-09 16:14:33 +0000541 # Setting O_TEMPORARY in the flags causes the OS to delete
542 # the file when it is closed. This is only supported by Windows.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000543 if _os.name == 'nt' and delete:
Guido van Rossum0e548712002-08-09 16:14:33 +0000544 flags |= _os.O_TEMPORARY
Tim Peters1baa22a2001-01-12 10:02:46 +0000545
Inada Naoki48274832021-03-29 12:28:14 +0900546 if "b" not in mode:
547 encoding = _io.text_encoding(encoding)
548
Gregory P. Smithad577b92015-05-22 16:18:14 -0700549 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type)
Victor Stinner1f99f9d2014-03-25 09:18:04 +0100550 try:
551 file = _io.open(fd, mode, buffering=buffering,
sth825aab92018-05-23 07:07:01 +0200552 newline=newline, encoding=encoding, errors=errors)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000553
Victor Stinner1f99f9d2014-03-25 09:18:04 +0100554 return _TemporaryFileWrapper(file, name, delete)
Martin Panter7869a222016-02-28 05:22:20 +0000555 except BaseException:
556 _os.unlink(name)
Victor Stinner1f99f9d2014-03-25 09:18:04 +0100557 _os.close(fd)
558 raise
Guido van Rossum0e548712002-08-09 16:14:33 +0000559
Steve Dower60419a72019-06-24 08:42:54 -0700560if _os.name != 'posix' or _sys.platform == 'cygwin':
Jason Tishler80c02af2002-08-14 15:10:09 +0000561 # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
562 # while it is open.
Guido van Rossum0e548712002-08-09 16:14:33 +0000563 TemporaryFile = NamedTemporaryFile
Tim Peters1baa22a2001-01-12 10:02:46 +0000564
565else:
Victor Stinnerd967fc92014-06-05 14:27:45 +0200566 # Is the O_TMPFILE flag available and does it work?
567 # The flag is set to False if os.open(dir, os.O_TMPFILE) raises an
568 # IsADirectoryError exception
569 _O_TMPFILE_WORKS = hasattr(_os, 'O_TMPFILE')
570
Guido van Rossumf0c74162007-08-28 03:29:45 +0000571 def TemporaryFile(mode='w+b', buffering=-1, encoding=None,
Gregory P. Smithad577b92015-05-22 16:18:14 -0700572 newline=None, suffix=None, prefix=None,
sth825aab92018-05-23 07:07:01 +0200573 dir=None, *, errors=None):
Guido van Rossum0e548712002-08-09 16:14:33 +0000574 """Create and return a temporary file.
575 Arguments:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000576 'prefix', 'suffix', 'dir' -- as for mkstemp.
Guido van Rossumf0c74162007-08-28 03:29:45 +0000577 'mode' -- the mode argument to io.open (default "w+b").
578 'buffering' -- the buffer size argument to io.open (default -1).
579 'encoding' -- the encoding argument to io.open (default None)
580 'newline' -- the newline argument to io.open (default None)
sth825aab92018-05-23 07:07:01 +0200581 'errors' -- the errors argument to io.open (default None)
Guido van Rossum0e548712002-08-09 16:14:33 +0000582 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000583
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000584 Returns an object with a file-like interface. The file has no
585 name, and will cease to exist when it is closed.
Guido van Rossum0e548712002-08-09 16:14:33 +0000586 """
Victor Stinnerd967fc92014-06-05 14:27:45 +0200587 global _O_TMPFILE_WORKS
Guido van Rossum0e548712002-08-09 16:14:33 +0000588
Inada Naoki48274832021-03-29 12:28:14 +0900589 if "b" not in mode:
590 encoding = _io.text_encoding(encoding)
591
Gregory P. Smithad577b92015-05-22 16:18:14 -0700592 prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
Guido van Rossume888cdc2002-08-17 14:50:24 +0000593
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000594 flags = _bin_openflags
Victor Stinnerd967fc92014-06-05 14:27:45 +0200595 if _O_TMPFILE_WORKS:
596 try:
597 flags2 = (flags | _os.O_TMPFILE) & ~_os.O_CREAT
598 fd = _os.open(dir, flags2, 0o600)
599 except IsADirectoryError:
Victor Stinner9aba8c82015-10-21 00:15:08 +0200600 # Linux kernel older than 3.11 ignores the O_TMPFILE flag:
601 # O_TMPFILE is read as O_DIRECTORY. Trying to open a directory
602 # with O_RDWR|O_DIRECTORY fails with IsADirectoryError, a
603 # directory cannot be open to write. Set flag to False to not
604 # try again.
Victor Stinnerd967fc92014-06-05 14:27:45 +0200605 _O_TMPFILE_WORKS = False
606 except OSError:
607 # The filesystem of the directory does not support O_TMPFILE.
608 # For example, OSError(95, 'Operation not supported').
Victor Stinner9aba8c82015-10-21 00:15:08 +0200609 #
610 # On Linux kernel older than 3.11, trying to open a regular
611 # file (or a symbolic link to a regular file) with O_TMPFILE
612 # fails with NotADirectoryError, because O_TMPFILE is read as
613 # O_DIRECTORY.
Victor Stinnerd967fc92014-06-05 14:27:45 +0200614 pass
615 else:
616 try:
617 return _io.open(fd, mode, buffering=buffering,
sth825aab92018-05-23 07:07:01 +0200618 newline=newline, encoding=encoding,
619 errors=errors)
Victor Stinnerd967fc92014-06-05 14:27:45 +0200620 except:
621 _os.close(fd)
622 raise
623 # Fallback to _mkstemp_inner().
Guido van Rossum0e548712002-08-09 16:14:33 +0000624
Gregory P. Smithad577b92015-05-22 16:18:14 -0700625 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type)
Guido van Rossum0e548712002-08-09 16:14:33 +0000626 try:
627 _os.unlink(name)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000628 return _io.open(fd, mode, buffering=buffering,
sth825aab92018-05-23 07:07:01 +0200629 newline=newline, encoding=encoding, errors=errors)
Guido van Rossum0e548712002-08-09 16:14:33 +0000630 except:
631 _os.close(fd)
632 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +0000633
634class SpooledTemporaryFile:
Serhiy Storchaka4f169a72013-02-09 11:46:42 +0200635 """Temporary file wrapper, specialized to switch from BytesIO
636 or StringIO to a real file when it exceeds a certain size or
Guido van Rossumd8faa362007-04-27 19:54:29 +0000637 when a fileno is needed.
638 """
639 _rolled = False
640
Guido van Rossumf0c74162007-08-28 03:29:45 +0000641 def __init__(self, max_size=0, mode='w+b', buffering=-1,
642 encoding=None, newline=None,
sth825aab92018-05-23 07:07:01 +0200643 suffix=None, prefix=None, dir=None, *, errors=None):
Guido van Rossum9a634702007-07-09 10:24:45 +0000644 if 'b' in mode:
645 self._file = _io.BytesIO()
646 else:
Inada Naoki48274832021-03-29 12:28:14 +0900647 encoding = _io.text_encoding(encoding)
Inada Naokiea9835c2019-11-27 22:22:06 +0900648 self._file = _io.TextIOWrapper(_io.BytesIO(),
649 encoding=encoding, errors=errors,
650 newline=newline)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000651 self._max_size = max_size
652 self._rolled = False
Guido van Rossumf0c74162007-08-28 03:29:45 +0000653 self._TemporaryFileArgs = {'mode': mode, 'buffering': buffering,
654 'suffix': suffix, 'prefix': prefix,
655 'encoding': encoding, 'newline': newline,
sth825aab92018-05-23 07:07:01 +0200656 'dir': dir, 'errors': errors}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000657
Guido van Rossum48b069a2020-04-07 09:50:06 -0700658 __class_getitem__ = classmethod(_types.GenericAlias)
Batuhan Taşkaya09c482f2019-12-30 19:08:08 +0300659
Guido van Rossumd8faa362007-04-27 19:54:29 +0000660 def _check(self, file):
661 if self._rolled: return
662 max_size = self._max_size
663 if max_size and file.tell() > max_size:
664 self.rollover()
665
666 def rollover(self):
667 if self._rolled: return
668 file = self._file
Guido van Rossumf0c74162007-08-28 03:29:45 +0000669 newfile = self._file = TemporaryFile(**self._TemporaryFileArgs)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000670 del self._TemporaryFileArgs
671
Inada Naokiea9835c2019-11-27 22:22:06 +0900672 pos = file.tell()
673 if hasattr(newfile, 'buffer'):
674 newfile.buffer.write(file.detach().getvalue())
675 else:
676 newfile.write(file.getvalue())
677 newfile.seek(pos, 0)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000678
679 self._rolled = True
680
Christian Heimes3ecfea712008-02-09 20:51:34 +0000681 # The method caching trick from NamedTemporaryFile
682 # won't work here, because _file may change from a
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300683 # BytesIO/StringIO instance to a real file. So we list
Christian Heimes3ecfea712008-02-09 20:51:34 +0000684 # all the methods directly.
685
686 # Context management protocol
687 def __enter__(self):
688 if self._file.closed:
689 raise ValueError("Cannot enter context with closed file")
690 return self
691
692 def __exit__(self, exc, value, tb):
693 self._file.close()
694
Guido van Rossumd8faa362007-04-27 19:54:29 +0000695 # file protocol
696 def __iter__(self):
697 return self._file.__iter__()
698
699 def close(self):
700 self._file.close()
701
702 @property
703 def closed(self):
704 return self._file.closed
705
706 @property
707 def encoding(self):
sth825aab92018-05-23 07:07:01 +0200708 return self._file.encoding
709
710 @property
711 def errors(self):
712 return self._file.errors
Guido van Rossumd8faa362007-04-27 19:54:29 +0000713
714 def fileno(self):
715 self.rollover()
716 return self._file.fileno()
717
718 def flush(self):
719 self._file.flush()
720
721 def isatty(self):
722 return self._file.isatty()
723
724 @property
725 def mode(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200726 try:
727 return self._file.mode
728 except AttributeError:
729 return self._TemporaryFileArgs['mode']
Guido van Rossumd8faa362007-04-27 19:54:29 +0000730
731 @property
732 def name(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200733 try:
734 return self._file.name
735 except AttributeError:
736 return None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000737
738 @property
739 def newlines(self):
sth825aab92018-05-23 07:07:01 +0200740 return self._file.newlines
Guido van Rossumd8faa362007-04-27 19:54:29 +0000741
742 def read(self, *args):
743 return self._file.read(*args)
744
745 def readline(self, *args):
746 return self._file.readline(*args)
747
748 def readlines(self, *args):
749 return self._file.readlines(*args)
750
751 def seek(self, *args):
Inada Naoki485e7152020-04-17 15:56:35 +0900752 return self._file.seek(*args)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000753
Guido van Rossumd8faa362007-04-27 19:54:29 +0000754 def tell(self):
755 return self._file.tell()
756
Antoine Pitrou0e86a582011-11-25 18:03:09 +0100757 def truncate(self, size=None):
758 if size is None:
759 self._file.truncate()
760 else:
761 if size > self._max_size:
762 self.rollover()
763 self._file.truncate(size)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000764
765 def write(self, s):
766 file = self._file
767 rv = file.write(s)
768 self._check(file)
769 return rv
770
771 def writelines(self, iterable):
772 file = self._file
773 rv = file.writelines(iterable)
774 self._check(file)
775 return rv
776
Nick Coghlan543af752010-10-24 11:23:25 +0000777
CAM Gerlachbd2fa3c2021-03-14 13:06:56 -0500778class TemporaryDirectory:
Nick Coghlan543af752010-10-24 11:23:25 +0000779 """Create and return a temporary directory. This has the same
780 behavior as mkdtemp but can be used as a context manager. For
781 example:
782
783 with TemporaryDirectory() as tmpdir:
784 ...
785
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300786 Upon exiting the context, the directory and everything contained
Nick Coghlan543af752010-10-24 11:23:25 +0000787 in it are removed.
788 """
789
CAM Gerlachbd2fa3c2021-03-14 13:06:56 -0500790 def __init__(self, suffix=None, prefix=None, dir=None,
791 ignore_cleanup_errors=False):
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000792 self.name = mkdtemp(suffix, prefix, dir)
CAM Gerlachbd2fa3c2021-03-14 13:06:56 -0500793 self._ignore_cleanup_errors = ignore_cleanup_errors
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200794 self._finalizer = _weakref.finalize(
795 self, self._cleanup, self.name,
CAM Gerlachbd2fa3c2021-03-14 13:06:56 -0500796 warn_message="Implicitly cleaning up {!r}".format(self),
797 ignore_errors=self._ignore_cleanup_errors)
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200798
799 @classmethod
CAM Gerlachbd2fa3c2021-03-14 13:06:56 -0500800 def _rmtree(cls, name, ignore_errors=False):
Serhiy Storchakae9b51c02019-05-31 11:30:37 +0300801 def onerror(func, path, exc_info):
802 if issubclass(exc_info[0], PermissionError):
803 def resetperms(path):
804 try:
805 _os.chflags(path, 0)
806 except AttributeError:
807 pass
808 _os.chmod(path, 0o700)
809
810 try:
811 if path != name:
812 resetperms(_os.path.dirname(path))
813 resetperms(path)
814
815 try:
816 _os.unlink(path)
817 # PermissionError is raised on FreeBSD for directories
818 except (IsADirectoryError, PermissionError):
CAM Gerlachbd2fa3c2021-03-14 13:06:56 -0500819 cls._rmtree(path, ignore_errors=ignore_errors)
Serhiy Storchakae9b51c02019-05-31 11:30:37 +0300820 except FileNotFoundError:
821 pass
822 elif issubclass(exc_info[0], FileNotFoundError):
823 pass
824 else:
CAM Gerlachbd2fa3c2021-03-14 13:06:56 -0500825 if not ignore_errors:
826 raise
Serhiy Storchakae9b51c02019-05-31 11:30:37 +0300827
828 _shutil.rmtree(name, onerror=onerror)
829
830 @classmethod
CAM Gerlachbd2fa3c2021-03-14 13:06:56 -0500831 def _cleanup(cls, name, warn_message, ignore_errors=False):
832 cls._rmtree(name, ignore_errors=ignore_errors)
Serhiy Storchaka5e193ac2014-09-24 13:26:25 +0300833 _warnings.warn(warn_message, ResourceWarning)
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200834
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000835 def __repr__(self):
836 return "<{} {!r}>".format(self.__class__.__name__, self.name)
Nick Coghlan543af752010-10-24 11:23:25 +0000837
838 def __enter__(self):
839 return self.name
840
Nick Coghlan543af752010-10-24 11:23:25 +0000841 def __exit__(self, exc, value, tb):
842 self.cleanup()
843
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200844 def cleanup(self):
CAM Gerlachbd2fa3c2021-03-14 13:06:56 -0500845 if self._finalizer.detach() or _os.path.exists(self.name):
846 self._rmtree(self.name, ignore_errors=self._ignore_cleanup_errors)
Batuhan Taşkaya03615562020-04-10 17:46:36 +0300847
848 __class_getitem__ = classmethod(_types.GenericAlias)