blob: 45709cb06cf4e67659b0f2b7266615c20c32989a [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
Serhiy Storchakaa28632b2014-01-27 11:21:54 +020047import weakref as _weakref
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020048import _thread
Guido van Rossuma0934242002-12-30 22:36:09 +000049_allocate_lock = _thread.allocate_lock
Guido van Rossum0e548712002-08-09 16:14:33 +000050
51_text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL
Tim Petersa0d55de2002-08-09 18:01:01 +000052if hasattr(_os, 'O_NOFOLLOW'):
53 _text_openflags |= _os.O_NOFOLLOW
Guido van Rossum0e548712002-08-09 16:14:33 +000054
55_bin_openflags = _text_openflags
Tim Petersa0d55de2002-08-09 18:01:01 +000056if hasattr(_os, 'O_BINARY'):
57 _bin_openflags |= _os.O_BINARY
Guido van Rossum0e548712002-08-09 16:14:33 +000058
59if hasattr(_os, 'TMP_MAX'):
60 TMP_MAX = _os.TMP_MAX
61else:
62 TMP_MAX = 10000
63
Gregory P. Smithad577b92015-05-22 16:18:14 -070064# This variable _was_ unused for legacy reasons, see issue 10354.
65# But as of 3.5 we actually use it at runtime so changing it would
66# have a possibly desirable side effect... But we do not want to support
67# that as an API. It is undocumented on purpose. Do not depend on this.
Tim Petersbd7b4c72002-08-13 23:33:56 +000068template = "tmp"
Guido van Rossum0e548712002-08-09 16:14:33 +000069
Guido van Rossum0e548712002-08-09 16:14:33 +000070# Internal routines.
71
72_once_lock = _allocate_lock()
73
Guido van Rossumb256159392003-11-10 02:16:36 +000074
75def _exists(fn):
76 try:
Anthony Sottile8377cd42019-02-25 14:32:27 -080077 _os.lstat(fn)
Florent Xicluna68f71a32011-10-28 16:06:23 +020078 except OSError:
Guido van Rossumb256159392003-11-10 02:16:36 +000079 return False
80 else:
81 return True
82
Gregory P. Smithad577b92015-05-22 16:18:14 -070083
84def _infer_return_type(*args):
85 """Look at the type of all args and divine their implied return type."""
86 return_type = None
87 for arg in args:
88 if arg is None:
89 continue
90 if isinstance(arg, bytes):
91 if return_type is str:
92 raise TypeError("Can't mix bytes and non-bytes in "
93 "path components.")
94 return_type = bytes
95 else:
96 if return_type is bytes:
97 raise TypeError("Can't mix bytes and non-bytes in "
98 "path components.")
99 return_type = str
100 if return_type is None:
101 return str # tempfile APIs return a str by default.
102 return return_type
103
104
105def _sanitize_params(prefix, suffix, dir):
106 """Common parameter processing for most APIs in this module."""
107 output_type = _infer_return_type(prefix, suffix, dir)
108 if suffix is None:
109 suffix = output_type()
110 if prefix is None:
111 if output_type is str:
112 prefix = template
113 else:
114 prefix = _os.fsencode(template)
115 if dir is None:
116 if output_type is str:
117 dir = gettempdir()
118 else:
119 dir = gettempdirb()
120 return prefix, suffix, dir, output_type
121
122
Victor Stinner1e62bf12017-04-19 22:59:51 +0200123class _RandomNameSequence:
124 """An instance of _RandomNameSequence generates an endless
125 sequence of unpredictable strings which can safely be incorporated
Wolfgang Maier9c463ec2018-04-09 02:42:39 +0200126 into file names. Each string is eight characters long. Multiple
Victor Stinner1e62bf12017-04-19 22:59:51 +0200127 threads can safely use the same instance at the same time.
128
129 _RandomNameSequence is an iterator."""
Guido van Rossum0e548712002-08-09 16:14:33 +0000130
Raymond Hettinger572895b2010-11-09 03:43:58 +0000131 characters = "abcdefghijklmnopqrstuvwxyz0123456789_"
Victor Stinner1e62bf12017-04-19 22:59:51 +0200132
133 @property
134 def rng(self):
Antoine Pitrou4558bad2011-11-25 21:28:15 +0100135 cur_pid = _os.getpid()
Victor Stinner1e62bf12017-04-19 22:59:51 +0200136 if cur_pid != getattr(self, '_rng_pid', None):
137 self._rng = _Random()
138 self._rng_pid = cur_pid
139 return self._rng
140
141 def __iter__(self):
142 return self
143
144 def __next__(self):
145 c = self.characters
146 choose = self.rng.choice
147 letters = [choose(c) for dummy in range(8)]
148 return ''.join(letters)
Guido van Rossum0e548712002-08-09 16:14:33 +0000149
150def _candidate_tempdir_list():
151 """Generate a list of candidate temporary directories which
152 _get_default_tempdir will try."""
153
154 dirlist = []
155
156 # First, try the environment.
157 for envname in 'TMPDIR', 'TEMP', 'TMP':
158 dirname = _os.getenv(envname)
159 if dirname: dirlist.append(dirname)
160
161 # Failing that, try OS-specific locations.
Alexandre Vassalottieca20b62008-05-16 02:54:33 +0000162 if _os.name == 'nt':
Steve Dowere5f41d22018-05-16 17:50:29 -0400163 dirlist.extend([ _os.path.expanduser(r'~\AppData\Local\Temp'),
164 _os.path.expandvars(r'%SYSTEMROOT%\Temp'),
165 r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
Guido van Rossum0e548712002-08-09 16:14:33 +0000166 else:
167 dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
168
169 # As a last resort, the current directory.
170 try:
171 dirlist.append(_os.getcwd())
Florent Xicluna68f71a32011-10-28 16:06:23 +0200172 except (AttributeError, OSError):
Guido van Rossum0e548712002-08-09 16:14:33 +0000173 dirlist.append(_os.curdir)
174
175 return dirlist
Tim Petersa0d55de2002-08-09 18:01:01 +0000176
Guido van Rossum0e548712002-08-09 16:14:33 +0000177def _get_default_tempdir():
178 """Calculate the default directory to use for temporary files.
Guido van Rossume888cdc2002-08-17 14:50:24 +0000179 This routine should be called exactly once.
Guido van Rossum0e548712002-08-09 16:14:33 +0000180
181 We determine whether or not a candidate temp dir is usable by
182 trying to create and write to a file in that directory. If this
183 is successful, the test file is deleted. To prevent denial of
184 service, the name of the test file must be randomized."""
185
186 namer = _RandomNameSequence()
187 dirlist = _candidate_tempdir_list()
Guido van Rossum0e548712002-08-09 16:14:33 +0000188
189 for dir in dirlist:
190 if dir != _os.curdir:
Tim Golden6d09f092013-10-25 18:38:16 +0100191 dir = _os.path.abspath(dir)
Guido van Rossum0e548712002-08-09 16:14:33 +0000192 # Try only a few names per directory.
Guido van Rossum805365e2007-05-07 22:24:25 +0000193 for seq in range(100):
Georg Brandla18af4e2007-04-21 15:47:16 +0000194 name = next(namer)
Guido van Rossum0e548712002-08-09 16:14:33 +0000195 filename = _os.path.join(dir, name)
196 try:
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000197 fd = _os.open(filename, _bin_openflags, 0o600)
Serhiy Storchakaf6b361e2013-02-13 00:35:30 +0200198 try:
199 try:
Serhiy Storchaka76a2ed12013-02-13 00:59:26 +0200200 with _io.open(fd, 'wb', closefd=False) as fp:
201 fp.write(b'blat')
Serhiy Storchakaf6b361e2013-02-13 00:35:30 +0200202 finally:
203 _os.close(fd)
204 finally:
205 _os.unlink(filename)
Guido van Rossum0e548712002-08-09 16:14:33 +0000206 return dir
Florent Xicluna68f71a32011-10-28 16:06:23 +0200207 except FileExistsError:
Guido van Rossum0e548712002-08-09 16:14:33 +0000208 pass
Serhiy Storchaka5d6b7b12015-05-20 00:11:48 +0300209 except PermissionError:
210 # This exception is thrown when a directory with the chosen name
211 # already exists on windows.
212 if (_os.name == 'nt' and _os.path.isdir(dir) and
213 _os.access(dir, _os.W_OK)):
214 continue
215 break # no point trying more names in this directory
Florent Xicluna68f71a32011-10-28 16:06:23 +0200216 except OSError:
217 break # no point trying more names in this directory
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200218 raise FileNotFoundError(_errno.ENOENT,
219 "No usable temporary directory found in %s" %
220 dirlist)
Guido van Rossum0e548712002-08-09 16:14:33 +0000221
Guido van Rossume888cdc2002-08-17 14:50:24 +0000222_name_sequence = None
223
Guido van Rossum0e548712002-08-09 16:14:33 +0000224def _get_candidate_names():
225 """Common setup sequence for all user-callable interfaces."""
226
Guido van Rossume888cdc2002-08-17 14:50:24 +0000227 global _name_sequence
228 if _name_sequence is None:
229 _once_lock.acquire()
230 try:
231 if _name_sequence is None:
232 _name_sequence = _RandomNameSequence()
233 finally:
234 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000235 return _name_sequence
Guido van Rossum41f95031992-03-31 19:02:01 +0000236
237
Gregory P. Smithad577b92015-05-22 16:18:14 -0700238def _mkstemp_inner(dir, pre, suf, flags, output_type):
Guido van Rossum0e548712002-08-09 16:14:33 +0000239 """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
Tim Peters9fadfb02001-01-13 03:04:02 +0000240
Guido van Rossum0e548712002-08-09 16:14:33 +0000241 names = _get_candidate_names()
Gregory P. Smithad577b92015-05-22 16:18:14 -0700242 if output_type is bytes:
243 names = map(_os.fsencode, names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000244
Guido van Rossum805365e2007-05-07 22:24:25 +0000245 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000246 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000247 file = _os.path.join(dir, pre + name + suf)
Steve Dower60419a72019-06-24 08:42:54 -0700248 _sys.audit("tempfile.mkstemp", file)
Guido van Rossum0e548712002-08-09 16:14:33 +0000249 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000250 fd = _os.open(file, flags, 0o600)
Florent Xicluna68f71a32011-10-28 16:06:23 +0200251 except FileExistsError:
252 continue # try again
Eli Benderskyf315df32013-09-06 06:11:19 -0700253 except PermissionError:
254 # This exception is thrown when a directory with the chosen name
255 # already exists on windows.
Serhiy Storchaka5d6b7b12015-05-20 00:11:48 +0300256 if (_os.name == 'nt' and _os.path.isdir(dir) and
257 _os.access(dir, _os.W_OK)):
Eli Benderskyf315df32013-09-06 06:11:19 -0700258 continue
259 else:
260 raise
Gregory P. Smithad577b92015-05-22 16:18:14 -0700261 return (fd, _os.path.abspath(file))
Guido van Rossum0e548712002-08-09 16:14:33 +0000262
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200263 raise FileExistsError(_errno.EEXIST,
264 "No usable temporary file name found")
Tim Petersa0d55de2002-08-09 18:01:01 +0000265
Guido van Rossum0e548712002-08-09 16:14:33 +0000266
267# User visible interfaces.
Guido van Rossumb0e57181998-10-14 20:27:05 +0000268
Guido van Rossum41f95031992-03-31 19:02:01 +0000269def gettempprefix():
Gregory P. Smithad577b92015-05-22 16:18:14 -0700270 """The default prefix for temporary directories."""
Guido van Rossum0e548712002-08-09 16:14:33 +0000271 return template
Tim Peters9fadfb02001-01-13 03:04:02 +0000272
Gregory P. Smithad577b92015-05-22 16:18:14 -0700273def gettempprefixb():
274 """The default prefix for temporary directories as bytes."""
275 return _os.fsencode(gettempprefix())
276
Guido van Rossume888cdc2002-08-17 14:50:24 +0000277tempdir = None
278
Guido van Rossum0e548712002-08-09 16:14:33 +0000279def gettempdir():
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000280 """Accessor for tempfile.tempdir."""
Guido van Rossume888cdc2002-08-17 14:50:24 +0000281 global tempdir
282 if tempdir is None:
283 _once_lock.acquire()
284 try:
285 if tempdir is None:
286 tempdir = _get_default_tempdir()
287 finally:
288 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000289 return tempdir
290
Gregory P. Smithad577b92015-05-22 16:18:14 -0700291def gettempdirb():
292 """A bytes version of tempfile.gettempdir()."""
293 return _os.fsencode(gettempdir())
294
295def mkstemp(suffix=None, prefix=None, dir=None, text=False):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000296 """User-callable function to create and return a unique temporary
Guido van Rossum0e548712002-08-09 16:14:33 +0000297 file. The return value is a pair (fd, name) where fd is the
298 file descriptor returned by os.open, and name is the filename.
299
Martin Panter9b566c32015-11-07 00:32:50 +0000300 If 'suffix' is not None, the file name will end with that suffix,
Guido van Rossum0e548712002-08-09 16:14:33 +0000301 otherwise there will be no suffix.
302
Martin Panter9b566c32015-11-07 00:32:50 +0000303 If 'prefix' is not None, the file name will begin with that prefix,
Guido van Rossum0e548712002-08-09 16:14:33 +0000304 otherwise a default prefix is used.
305
Martin Panter9b566c32015-11-07 00:32:50 +0000306 If 'dir' is not None, the file will be created in that directory,
Guido van Rossum0e548712002-08-09 16:14:33 +0000307 otherwise a default directory is used.
308
Tim Peters04490bf2002-08-14 15:41:26 +0000309 If 'text' is specified and true, the file is opened in text
310 mode. Else (the default) the file is opened in binary mode. On
311 some operating systems, this makes no difference.
Guido van Rossum0e548712002-08-09 16:14:33 +0000312
Martin Panter9b566c32015-11-07 00:32:50 +0000313 If any of 'suffix', 'prefix' and 'dir' are not None, they must be the
314 same type. If they are bytes, the returned name will be bytes; str
315 otherwise.
Gregory P. Smithad577b92015-05-22 16:18:14 -0700316
Guido van Rossum0e548712002-08-09 16:14:33 +0000317 The file is readable and writable only by the creating user ID.
318 If the operating system uses permission bits to indicate whether a
319 file is executable, the file is executable by no one. The file
320 descriptor is not inherited by children of this process.
321
322 Caller is responsible for deleting the file when done with it.
Tim Peters9fadfb02001-01-13 03:04:02 +0000323 """
324
Gregory P. Smithad577b92015-05-22 16:18:14 -0700325 prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
Guido van Rossume888cdc2002-08-17 14:50:24 +0000326
Tim Peters04490bf2002-08-14 15:41:26 +0000327 if text:
Guido van Rossum0e548712002-08-09 16:14:33 +0000328 flags = _text_openflags
Tim Peters04490bf2002-08-14 15:41:26 +0000329 else:
330 flags = _bin_openflags
Guido van Rossum0e548712002-08-09 16:14:33 +0000331
Gregory P. Smithad577b92015-05-22 16:18:14 -0700332 return _mkstemp_inner(dir, prefix, suffix, flags, output_type)
Guido van Rossumcff34541992-01-14 18:31:56 +0000333
Guido van Rossumeee94981991-11-12 15:38:08 +0000334
Gregory P. Smithad577b92015-05-22 16:18:14 -0700335def mkdtemp(suffix=None, prefix=None, dir=None):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000336 """User-callable function to create and return a unique temporary
Guido van Rossum0e548712002-08-09 16:14:33 +0000337 directory. The return value is the pathname of the directory.
338
Tim Peters04490bf2002-08-14 15:41:26 +0000339 Arguments are as for mkstemp, except that the 'text' argument is
Guido van Rossum0e548712002-08-09 16:14:33 +0000340 not accepted.
341
342 The directory is readable, writable, and searchable only by the
343 creating user.
344
345 Caller is responsible for deleting the directory when done with it.
346 """
347
Gregory P. Smithad577b92015-05-22 16:18:14 -0700348 prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
Guido van Rossume888cdc2002-08-17 14:50:24 +0000349
Guido van Rossum0e548712002-08-09 16:14:33 +0000350 names = _get_candidate_names()
Gregory P. Smithad577b92015-05-22 16:18:14 -0700351 if output_type is bytes:
352 names = map(_os.fsencode, names)
Tim Petersa0d55de2002-08-09 18:01:01 +0000353
Guido van Rossum805365e2007-05-07 22:24:25 +0000354 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000355 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000356 file = _os.path.join(dir, prefix + name + suffix)
Steve Dower60419a72019-06-24 08:42:54 -0700357 _sys.audit("tempfile.mkdtemp", file)
Guido van Rossum0e548712002-08-09 16:14:33 +0000358 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000359 _os.mkdir(file, 0o700)
Florent Xicluna68f71a32011-10-28 16:06:23 +0200360 except FileExistsError:
361 continue # try again
Serhiy Storchaka5d6b7b12015-05-20 00:11:48 +0300362 except PermissionError:
363 # This exception is thrown when a directory with the chosen name
364 # already exists on windows.
365 if (_os.name == 'nt' and _os.path.isdir(dir) and
366 _os.access(dir, _os.W_OK)):
367 continue
368 else:
369 raise
Gregory P. Smithad577b92015-05-22 16:18:14 -0700370 return file
Guido van Rossum0e548712002-08-09 16:14:33 +0000371
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200372 raise FileExistsError(_errno.EEXIST,
373 "No usable temporary directory name found")
Guido van Rossum0e548712002-08-09 16:14:33 +0000374
Guido van Rossume888cdc2002-08-17 14:50:24 +0000375def mktemp(suffix="", prefix=template, dir=None):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000376 """User-callable function to return a unique temporary file name. The
Guido van Rossum0e548712002-08-09 16:14:33 +0000377 file is not created.
378
Martin Panter9b566c32015-11-07 00:32:50 +0000379 Arguments are similar to mkstemp, except that the 'text' argument is
380 not accepted, and suffix=None, prefix=None and bytes file names are not
381 supported.
Guido van Rossum0e548712002-08-09 16:14:33 +0000382
Gregory P. Smithad577b92015-05-22 16:18:14 -0700383 THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may
384 refer to a file that did not exist at some point, but by the time
Guido van Rossum0e548712002-08-09 16:14:33 +0000385 you get around to creating it, someone else may have beaten you to
386 the punch.
387 """
388
Guido van Rossum44f602d2002-11-22 15:56:29 +0000389## from warnings import warn as _warn
390## _warn("mktemp is a potential security risk to your program",
391## RuntimeWarning, stacklevel=2)
Guido van Rossum0e548712002-08-09 16:14:33 +0000392
Guido van Rossume888cdc2002-08-17 14:50:24 +0000393 if dir is None:
394 dir = gettempdir()
395
Guido van Rossum0e548712002-08-09 16:14:33 +0000396 names = _get_candidate_names()
Guido van Rossum805365e2007-05-07 22:24:25 +0000397 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000398 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000399 file = _os.path.join(dir, prefix + name + suffix)
Guido van Rossumb256159392003-11-10 02:16:36 +0000400 if not _exists(file):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000401 return file
Guido van Rossumca549821997-08-12 18:00:12 +0000402
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200403 raise FileExistsError(_errno.EEXIST,
404 "No usable temporary filename found")
Guido van Rossumca549821997-08-12 18:00:12 +0000405
Christian Heimes3ecfea712008-02-09 20:51:34 +0000406
Antoine Pitrou17c93262013-12-21 22:14:56 +0100407class _TemporaryFileCloser:
408 """A separate object allowing proper closing of a temporary file's
409 underlying file object, without adding a __del__ method to the
410 temporary file."""
Tim Petersa255a722001-12-18 22:32:40 +0000411
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200412 file = None # Set here since __del__ checks it
Serhiy Storchaka99e033b2014-01-27 11:18:27 +0200413 close_called = False
414
Guido van Rossumd8faa362007-04-27 19:54:29 +0000415 def __init__(self, file, name, delete=True):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000416 self.file = file
Guido van Rossum0e548712002-08-09 16:14:33 +0000417 self.name = name
Guido van Rossumd8faa362007-04-27 19:54:29 +0000418 self.delete = delete
Guido van Rossumca549821997-08-12 18:00:12 +0000419
Guido van Rossum0e548712002-08-09 16:14:33 +0000420 # NT provides delete-on-close as a primitive, so we don't need
421 # the wrapper to do anything special. We still use it so that
422 # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
423 if _os.name != 'nt':
Guido van Rossum0e548712002-08-09 16:14:33 +0000424 # Cache the unlinker so we don't get spurious errors at
425 # shutdown when the module-level "os" is None'd out. Note
426 # that this must be referenced as self.unlink, because the
427 # name TemporaryFileWrapper may also get None'd out before
428 # __del__ is called.
Tim Peters1baa22a2001-01-12 10:02:46 +0000429
Serhiy Storchaka99e033b2014-01-27 11:18:27 +0200430 def close(self, unlink=_os.unlink):
431 if not self.close_called and self.file is not None:
Tim Peters6ef966e2002-11-21 15:48:33 +0000432 self.close_called = True
Serhiy Storchaka7e7a3db2015-04-10 13:24:41 +0300433 try:
434 self.file.close()
435 finally:
436 if self.delete:
437 unlink(self.name)
Tim Peters1baa22a2001-01-12 10:02:46 +0000438
Antoine Pitrou17c93262013-12-21 22:14:56 +0100439 # Need to ensure the file is deleted on __del__
Guido van Rossum0e548712002-08-09 16:14:33 +0000440 def __del__(self):
441 self.close()
Tim Peters1baa22a2001-01-12 10:02:46 +0000442
Benjamin Peterson98d23f22009-06-30 22:27:25 +0000443 else:
Antoine Pitrou17c93262013-12-21 22:14:56 +0100444 def close(self):
445 if not self.close_called:
446 self.close_called = True
447 self.file.close()
448
449
450class _TemporaryFileWrapper:
451 """Temporary file wrapper
452
453 This class provides a wrapper around files opened for
454 temporary use. In particular, it seeks to automatically
455 remove the file when it is no longer needed.
456 """
457
458 def __init__(self, file, name, delete=True):
459 self.file = file
460 self.name = name
461 self.delete = delete
462 self._closer = _TemporaryFileCloser(file, name, delete)
463
464 def __getattr__(self, name):
465 # Attribute lookups are delegated to the underlying file
466 # and cached for non-numeric results
467 # (i.e. methods are cached, closed and friends are not)
468 file = self.__dict__['file']
469 a = getattr(file, name)
470 if hasattr(a, '__call__'):
471 func = a
472 @_functools.wraps(func)
473 def func_wrapper(*args, **kwargs):
474 return func(*args, **kwargs)
475 # Avoid closing the file as long as the wrapper is alive,
476 # see issue #18879.
477 func_wrapper._closer = self._closer
478 a = func_wrapper
479 if not isinstance(a, int):
480 setattr(self, name, a)
481 return a
482
483 # The underlying __enter__ method returns the wrong object
484 # (self.file) so override it to return the wrapper
485 def __enter__(self):
486 self.file.__enter__()
487 return self
488
489 # Need to trap __exit__ as well to ensure the file gets
490 # deleted when used in a with statement
491 def __exit__(self, exc, value, tb):
492 result = self.file.__exit__(exc, value, tb)
493 self.close()
494 return result
495
496 def close(self):
497 """
498 Close the temporary file, possibly deleting it.
499 """
500 self._closer.close()
501
502 # iter() doesn't use __getattr__ to find the __iter__ method
503 def __iter__(self):
Serhiy Storchakad83b7c22015-03-20 16:11:20 +0200504 # Don't return iter(self.file), but yield from it to avoid closing
R David Murray75ed90a2015-03-22 12:33:46 -0400505 # file as long as it's being used as iterator (see issue #23700). We
506 # can't use 'yield from' here because iter(file) returns the file
507 # object itself, which has a close method, and thus the file would get
508 # closed when the generator is finalized, due to PEP380 semantics.
Serhiy Storchakad83b7c22015-03-20 16:11:20 +0200509 for line in self.file:
510 yield line
Christian Heimes3ecfea712008-02-09 20:51:34 +0000511
512
Guido van Rossumf0c74162007-08-28 03:29:45 +0000513def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None,
Gregory P. Smithad577b92015-05-22 16:18:14 -0700514 newline=None, suffix=None, prefix=None,
sth825aab92018-05-23 07:07:01 +0200515 dir=None, delete=True, *, errors=None):
Guido van Rossum0e548712002-08-09 16:14:33 +0000516 """Create and return a temporary file.
517 Arguments:
518 'prefix', 'suffix', 'dir' -- as for mkstemp.
Guido van Rossumf0c74162007-08-28 03:29:45 +0000519 'mode' -- the mode argument to io.open (default "w+b").
520 'buffering' -- the buffer size argument to io.open (default -1).
521 'encoding' -- the encoding argument to io.open (default None)
522 'newline' -- the newline argument to io.open (default None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000523 'delete' -- whether the file is deleted on close (default True).
sth825aab92018-05-23 07:07:01 +0200524 'errors' -- the errors argument to io.open (default None)
Guido van Rossum0e548712002-08-09 16:14:33 +0000525 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000526
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000527 Returns an object with a file-like interface; the name of the file
Martin Panter1f0e1f32016-02-22 10:10:00 +0000528 is accessible as its 'name' attribute. The file will be automatically
529 deleted when it is closed unless the 'delete' argument is set to False.
Guido van Rossum0e548712002-08-09 16:14:33 +0000530 """
Tim Peters1baa22a2001-01-12 10:02:46 +0000531
Gregory P. Smithad577b92015-05-22 16:18:14 -0700532 prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
Guido van Rossume888cdc2002-08-17 14:50:24 +0000533
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000534 flags = _bin_openflags
Tim Peters1baa22a2001-01-12 10:02:46 +0000535
Guido van Rossum0e548712002-08-09 16:14:33 +0000536 # Setting O_TEMPORARY in the flags causes the OS to delete
537 # the file when it is closed. This is only supported by Windows.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000538 if _os.name == 'nt' and delete:
Guido van Rossum0e548712002-08-09 16:14:33 +0000539 flags |= _os.O_TEMPORARY
Tim Peters1baa22a2001-01-12 10:02:46 +0000540
Gregory P. Smithad577b92015-05-22 16:18:14 -0700541 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type)
Victor Stinner1f99f9d2014-03-25 09:18:04 +0100542 try:
543 file = _io.open(fd, mode, buffering=buffering,
sth825aab92018-05-23 07:07:01 +0200544 newline=newline, encoding=encoding, errors=errors)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000545
Victor Stinner1f99f9d2014-03-25 09:18:04 +0100546 return _TemporaryFileWrapper(file, name, delete)
Martin Panter7869a222016-02-28 05:22:20 +0000547 except BaseException:
548 _os.unlink(name)
Victor Stinner1f99f9d2014-03-25 09:18:04 +0100549 _os.close(fd)
550 raise
Guido van Rossum0e548712002-08-09 16:14:33 +0000551
Steve Dower60419a72019-06-24 08:42:54 -0700552if _os.name != 'posix' or _sys.platform == 'cygwin':
Jason Tishler80c02af2002-08-14 15:10:09 +0000553 # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
554 # while it is open.
Guido van Rossum0e548712002-08-09 16:14:33 +0000555 TemporaryFile = NamedTemporaryFile
Tim Peters1baa22a2001-01-12 10:02:46 +0000556
557else:
Victor Stinnerd967fc92014-06-05 14:27:45 +0200558 # Is the O_TMPFILE flag available and does it work?
559 # The flag is set to False if os.open(dir, os.O_TMPFILE) raises an
560 # IsADirectoryError exception
561 _O_TMPFILE_WORKS = hasattr(_os, 'O_TMPFILE')
562
Guido van Rossumf0c74162007-08-28 03:29:45 +0000563 def TemporaryFile(mode='w+b', buffering=-1, encoding=None,
Gregory P. Smithad577b92015-05-22 16:18:14 -0700564 newline=None, suffix=None, prefix=None,
sth825aab92018-05-23 07:07:01 +0200565 dir=None, *, errors=None):
Guido van Rossum0e548712002-08-09 16:14:33 +0000566 """Create and return a temporary file.
567 Arguments:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000568 'prefix', 'suffix', 'dir' -- as for mkstemp.
Guido van Rossumf0c74162007-08-28 03:29:45 +0000569 'mode' -- the mode argument to io.open (default "w+b").
570 'buffering' -- the buffer size argument to io.open (default -1).
571 'encoding' -- the encoding argument to io.open (default None)
572 'newline' -- the newline argument to io.open (default None)
sth825aab92018-05-23 07:07:01 +0200573 'errors' -- the errors argument to io.open (default None)
Guido van Rossum0e548712002-08-09 16:14:33 +0000574 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000575
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000576 Returns an object with a file-like interface. The file has no
577 name, and will cease to exist when it is closed.
Guido van Rossum0e548712002-08-09 16:14:33 +0000578 """
Victor Stinnerd967fc92014-06-05 14:27:45 +0200579 global _O_TMPFILE_WORKS
Guido van Rossum0e548712002-08-09 16:14:33 +0000580
Gregory P. Smithad577b92015-05-22 16:18:14 -0700581 prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
Guido van Rossume888cdc2002-08-17 14:50:24 +0000582
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000583 flags = _bin_openflags
Victor Stinnerd967fc92014-06-05 14:27:45 +0200584 if _O_TMPFILE_WORKS:
585 try:
586 flags2 = (flags | _os.O_TMPFILE) & ~_os.O_CREAT
587 fd = _os.open(dir, flags2, 0o600)
588 except IsADirectoryError:
Victor Stinner9aba8c82015-10-21 00:15:08 +0200589 # Linux kernel older than 3.11 ignores the O_TMPFILE flag:
590 # O_TMPFILE is read as O_DIRECTORY. Trying to open a directory
591 # with O_RDWR|O_DIRECTORY fails with IsADirectoryError, a
592 # directory cannot be open to write. Set flag to False to not
593 # try again.
Victor Stinnerd967fc92014-06-05 14:27:45 +0200594 _O_TMPFILE_WORKS = False
595 except OSError:
596 # The filesystem of the directory does not support O_TMPFILE.
597 # For example, OSError(95, 'Operation not supported').
Victor Stinner9aba8c82015-10-21 00:15:08 +0200598 #
599 # On Linux kernel older than 3.11, trying to open a regular
600 # file (or a symbolic link to a regular file) with O_TMPFILE
601 # fails with NotADirectoryError, because O_TMPFILE is read as
602 # O_DIRECTORY.
Victor Stinnerd967fc92014-06-05 14:27:45 +0200603 pass
604 else:
605 try:
606 return _io.open(fd, mode, buffering=buffering,
sth825aab92018-05-23 07:07:01 +0200607 newline=newline, encoding=encoding,
608 errors=errors)
Victor Stinnerd967fc92014-06-05 14:27:45 +0200609 except:
610 _os.close(fd)
611 raise
612 # Fallback to _mkstemp_inner().
Guido van Rossum0e548712002-08-09 16:14:33 +0000613
Gregory P. Smithad577b92015-05-22 16:18:14 -0700614 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type)
Guido van Rossum0e548712002-08-09 16:14:33 +0000615 try:
616 _os.unlink(name)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000617 return _io.open(fd, mode, buffering=buffering,
sth825aab92018-05-23 07:07:01 +0200618 newline=newline, encoding=encoding, errors=errors)
Guido van Rossum0e548712002-08-09 16:14:33 +0000619 except:
620 _os.close(fd)
621 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +0000622
623class SpooledTemporaryFile:
Serhiy Storchaka4f169a72013-02-09 11:46:42 +0200624 """Temporary file wrapper, specialized to switch from BytesIO
625 or StringIO to a real file when it exceeds a certain size or
Guido van Rossumd8faa362007-04-27 19:54:29 +0000626 when a fileno is needed.
627 """
628 _rolled = False
629
Guido van Rossumf0c74162007-08-28 03:29:45 +0000630 def __init__(self, max_size=0, mode='w+b', buffering=-1,
631 encoding=None, newline=None,
sth825aab92018-05-23 07:07:01 +0200632 suffix=None, prefix=None, dir=None, *, errors=None):
Guido van Rossum9a634702007-07-09 10:24:45 +0000633 if 'b' in mode:
634 self._file = _io.BytesIO()
635 else:
Guido van Rossum5d212552007-10-29 16:42:51 +0000636 # Setting newline="\n" avoids newline translation;
637 # this is important because otherwise on Windows we'd
Yury Selivanov0b866602014-09-26 17:08:21 -0400638 # get double newline translation upon rollover().
Alexandre Vassalotti3ade6f92008-06-12 01:13:54 +0000639 self._file = _io.StringIO(newline="\n")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000640 self._max_size = max_size
641 self._rolled = False
Guido van Rossumf0c74162007-08-28 03:29:45 +0000642 self._TemporaryFileArgs = {'mode': mode, 'buffering': buffering,
643 'suffix': suffix, 'prefix': prefix,
644 'encoding': encoding, 'newline': newline,
sth825aab92018-05-23 07:07:01 +0200645 'dir': dir, 'errors': errors}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000646
647 def _check(self, file):
648 if self._rolled: return
649 max_size = self._max_size
650 if max_size and file.tell() > max_size:
651 self.rollover()
652
653 def rollover(self):
654 if self._rolled: return
655 file = self._file
Guido van Rossumf0c74162007-08-28 03:29:45 +0000656 newfile = self._file = TemporaryFile(**self._TemporaryFileArgs)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000657 del self._TemporaryFileArgs
658
659 newfile.write(file.getvalue())
660 newfile.seek(file.tell(), 0)
661
662 self._rolled = True
663
Christian Heimes3ecfea712008-02-09 20:51:34 +0000664 # The method caching trick from NamedTemporaryFile
665 # won't work here, because _file may change from a
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300666 # BytesIO/StringIO instance to a real file. So we list
Christian Heimes3ecfea712008-02-09 20:51:34 +0000667 # all the methods directly.
668
669 # Context management protocol
670 def __enter__(self):
671 if self._file.closed:
672 raise ValueError("Cannot enter context with closed file")
673 return self
674
675 def __exit__(self, exc, value, tb):
676 self._file.close()
677
Guido van Rossumd8faa362007-04-27 19:54:29 +0000678 # file protocol
679 def __iter__(self):
680 return self._file.__iter__()
681
682 def close(self):
683 self._file.close()
684
685 @property
686 def closed(self):
687 return self._file.closed
688
689 @property
690 def encoding(self):
sth825aab92018-05-23 07:07:01 +0200691 return self._file.encoding
692
693 @property
694 def errors(self):
695 return self._file.errors
Guido van Rossumd8faa362007-04-27 19:54:29 +0000696
697 def fileno(self):
698 self.rollover()
699 return self._file.fileno()
700
701 def flush(self):
702 self._file.flush()
703
704 def isatty(self):
705 return self._file.isatty()
706
707 @property
708 def mode(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200709 try:
710 return self._file.mode
711 except AttributeError:
712 return self._TemporaryFileArgs['mode']
Guido van Rossumd8faa362007-04-27 19:54:29 +0000713
714 @property
715 def name(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200716 try:
717 return self._file.name
718 except AttributeError:
719 return None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000720
721 @property
722 def newlines(self):
sth825aab92018-05-23 07:07:01 +0200723 return self._file.newlines
Guido van Rossumd8faa362007-04-27 19:54:29 +0000724
725 def read(self, *args):
726 return self._file.read(*args)
727
728 def readline(self, *args):
729 return self._file.readline(*args)
730
731 def readlines(self, *args):
732 return self._file.readlines(*args)
733
734 def seek(self, *args):
735 self._file.seek(*args)
736
737 @property
738 def softspace(self):
739 return self._file.softspace
740
741 def tell(self):
742 return self._file.tell()
743
Antoine Pitrou0e86a582011-11-25 18:03:09 +0100744 def truncate(self, size=None):
745 if size is None:
746 self._file.truncate()
747 else:
748 if size > self._max_size:
749 self.rollover()
750 self._file.truncate(size)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000751
752 def write(self, s):
753 file = self._file
754 rv = file.write(s)
755 self._check(file)
756 return rv
757
758 def writelines(self, iterable):
759 file = self._file
760 rv = file.writelines(iterable)
761 self._check(file)
762 return rv
763
Nick Coghlan543af752010-10-24 11:23:25 +0000764
765class TemporaryDirectory(object):
766 """Create and return a temporary directory. This has the same
767 behavior as mkdtemp but can be used as a context manager. For
768 example:
769
770 with TemporaryDirectory() as tmpdir:
771 ...
772
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300773 Upon exiting the context, the directory and everything contained
Nick Coghlan543af752010-10-24 11:23:25 +0000774 in it are removed.
775 """
776
Gregory P. Smithad577b92015-05-22 16:18:14 -0700777 def __init__(self, suffix=None, prefix=None, dir=None):
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000778 self.name = mkdtemp(suffix, prefix, dir)
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200779 self._finalizer = _weakref.finalize(
780 self, self._cleanup, self.name,
781 warn_message="Implicitly cleaning up {!r}".format(self))
782
783 @classmethod
Serhiy Storchakae9b51c02019-05-31 11:30:37 +0300784 def _rmtree(cls, name):
785 def onerror(func, path, exc_info):
786 if issubclass(exc_info[0], PermissionError):
787 def resetperms(path):
788 try:
789 _os.chflags(path, 0)
790 except AttributeError:
791 pass
792 _os.chmod(path, 0o700)
793
794 try:
795 if path != name:
796 resetperms(_os.path.dirname(path))
797 resetperms(path)
798
799 try:
800 _os.unlink(path)
801 # PermissionError is raised on FreeBSD for directories
802 except (IsADirectoryError, PermissionError):
803 cls._rmtree(path)
804 except FileNotFoundError:
805 pass
806 elif issubclass(exc_info[0], FileNotFoundError):
807 pass
808 else:
809 raise
810
811 _shutil.rmtree(name, onerror=onerror)
812
813 @classmethod
Serhiy Storchaka5e193ac2014-09-24 13:26:25 +0300814 def _cleanup(cls, name, warn_message):
Serhiy Storchakae9b51c02019-05-31 11:30:37 +0300815 cls._rmtree(name)
Serhiy Storchaka5e193ac2014-09-24 13:26:25 +0300816 _warnings.warn(warn_message, ResourceWarning)
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200817
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000818 def __repr__(self):
819 return "<{} {!r}>".format(self.__class__.__name__, self.name)
Nick Coghlan543af752010-10-24 11:23:25 +0000820
821 def __enter__(self):
822 return self.name
823
Nick Coghlan543af752010-10-24 11:23:25 +0000824 def __exit__(self, exc, value, tb):
825 self.cleanup()
826
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200827 def cleanup(self):
Serhiy Storchaka5e193ac2014-09-24 13:26:25 +0300828 if self._finalizer.detach():
Serhiy Storchakae9b51c02019-05-31 11:30:37 +0300829 self._rmtree(self.name)