blob: ba04be8f9058e1b27fdcfc39f8c31883e51ad016 [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:
102 return str # tempfile APIs return a str by default.
103 return return_type
104
105
106def _sanitize_params(prefix, suffix, dir):
107 """Common parameter processing for most APIs in this module."""
108 output_type = _infer_return_type(prefix, suffix, dir)
109 if suffix is None:
110 suffix = output_type()
111 if prefix is None:
112 if output_type is str:
113 prefix = template
114 else:
115 prefix = _os.fsencode(template)
116 if dir is None:
117 if output_type is str:
118 dir = gettempdir()
119 else:
120 dir = gettempdirb()
121 return prefix, suffix, dir, output_type
122
123
Victor Stinner1e62bf12017-04-19 22:59:51 +0200124class _RandomNameSequence:
125 """An instance of _RandomNameSequence generates an endless
126 sequence of unpredictable strings which can safely be incorporated
Wolfgang Maier9c463ec2018-04-09 02:42:39 +0200127 into file names. Each string is eight characters long. Multiple
Victor Stinner1e62bf12017-04-19 22:59:51 +0200128 threads can safely use the same instance at the same time.
129
130 _RandomNameSequence is an iterator."""
Guido van Rossum0e548712002-08-09 16:14:33 +0000131
Raymond Hettinger572895b2010-11-09 03:43:58 +0000132 characters = "abcdefghijklmnopqrstuvwxyz0123456789_"
Victor Stinner1e62bf12017-04-19 22:59:51 +0200133
134 @property
135 def rng(self):
Antoine Pitrou4558bad2011-11-25 21:28:15 +0100136 cur_pid = _os.getpid()
Victor Stinner1e62bf12017-04-19 22:59:51 +0200137 if cur_pid != getattr(self, '_rng_pid', None):
138 self._rng = _Random()
139 self._rng_pid = cur_pid
140 return self._rng
141
142 def __iter__(self):
143 return self
144
145 def __next__(self):
146 c = self.characters
147 choose = self.rng.choice
148 letters = [choose(c) for dummy in range(8)]
149 return ''.join(letters)
Guido van Rossum0e548712002-08-09 16:14:33 +0000150
151def _candidate_tempdir_list():
152 """Generate a list of candidate temporary directories which
153 _get_default_tempdir will try."""
154
155 dirlist = []
156
157 # First, try the environment.
158 for envname in 'TMPDIR', 'TEMP', 'TMP':
159 dirname = _os.getenv(envname)
160 if dirname: dirlist.append(dirname)
161
162 # Failing that, try OS-specific locations.
Alexandre Vassalottieca20b62008-05-16 02:54:33 +0000163 if _os.name == 'nt':
Steve Dowere5f41d22018-05-16 17:50:29 -0400164 dirlist.extend([ _os.path.expanduser(r'~\AppData\Local\Temp'),
165 _os.path.expandvars(r'%SYSTEMROOT%\Temp'),
166 r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
Guido van Rossum0e548712002-08-09 16:14:33 +0000167 else:
168 dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
169
170 # As a last resort, the current directory.
171 try:
172 dirlist.append(_os.getcwd())
Florent Xicluna68f71a32011-10-28 16:06:23 +0200173 except (AttributeError, OSError):
Guido van Rossum0e548712002-08-09 16:14:33 +0000174 dirlist.append(_os.curdir)
175
176 return dirlist
Tim Petersa0d55de2002-08-09 18:01:01 +0000177
Guido van Rossum0e548712002-08-09 16:14:33 +0000178def _get_default_tempdir():
179 """Calculate the default directory to use for temporary files.
Guido van Rossume888cdc2002-08-17 14:50:24 +0000180 This routine should be called exactly once.
Guido van Rossum0e548712002-08-09 16:14:33 +0000181
182 We determine whether or not a candidate temp dir is usable by
183 trying to create and write to a file in that directory. If this
184 is successful, the test file is deleted. To prevent denial of
185 service, the name of the test file must be randomized."""
186
187 namer = _RandomNameSequence()
188 dirlist = _candidate_tempdir_list()
Guido van Rossum0e548712002-08-09 16:14:33 +0000189
190 for dir in dirlist:
191 if dir != _os.curdir:
Tim Golden6d09f092013-10-25 18:38:16 +0100192 dir = _os.path.abspath(dir)
Guido van Rossum0e548712002-08-09 16:14:33 +0000193 # Try only a few names per directory.
Guido van Rossum805365e2007-05-07 22:24:25 +0000194 for seq in range(100):
Georg Brandla18af4e2007-04-21 15:47:16 +0000195 name = next(namer)
Guido van Rossum0e548712002-08-09 16:14:33 +0000196 filename = _os.path.join(dir, name)
197 try:
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000198 fd = _os.open(filename, _bin_openflags, 0o600)
Serhiy Storchakaf6b361e2013-02-13 00:35:30 +0200199 try:
200 try:
Serhiy Storchaka76a2ed12013-02-13 00:59:26 +0200201 with _io.open(fd, 'wb', closefd=False) as fp:
202 fp.write(b'blat')
Serhiy Storchakaf6b361e2013-02-13 00:35:30 +0200203 finally:
204 _os.close(fd)
205 finally:
206 _os.unlink(filename)
Guido van Rossum0e548712002-08-09 16:14:33 +0000207 return dir
Florent Xicluna68f71a32011-10-28 16:06:23 +0200208 except FileExistsError:
Guido van Rossum0e548712002-08-09 16:14:33 +0000209 pass
Serhiy Storchaka5d6b7b12015-05-20 00:11:48 +0300210 except PermissionError:
211 # This exception is thrown when a directory with the chosen name
212 # already exists on windows.
213 if (_os.name == 'nt' and _os.path.isdir(dir) and
214 _os.access(dir, _os.W_OK)):
215 continue
216 break # no point trying more names in this directory
Florent Xicluna68f71a32011-10-28 16:06:23 +0200217 except OSError:
218 break # no point trying more names in this directory
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200219 raise FileNotFoundError(_errno.ENOENT,
220 "No usable temporary directory found in %s" %
221 dirlist)
Guido van Rossum0e548712002-08-09 16:14:33 +0000222
Guido van Rossume888cdc2002-08-17 14:50:24 +0000223_name_sequence = None
224
Guido van Rossum0e548712002-08-09 16:14:33 +0000225def _get_candidate_names():
226 """Common setup sequence for all user-callable interfaces."""
227
Guido van Rossume888cdc2002-08-17 14:50:24 +0000228 global _name_sequence
229 if _name_sequence is None:
230 _once_lock.acquire()
231 try:
232 if _name_sequence is None:
233 _name_sequence = _RandomNameSequence()
234 finally:
235 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000236 return _name_sequence
Guido van Rossum41f95031992-03-31 19:02:01 +0000237
238
Gregory P. Smithad577b92015-05-22 16:18:14 -0700239def _mkstemp_inner(dir, pre, suf, flags, output_type):
Guido van Rossum0e548712002-08-09 16:14:33 +0000240 """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
Tim Peters9fadfb02001-01-13 03:04:02 +0000241
Guido van Rossum0e548712002-08-09 16:14:33 +0000242 names = _get_candidate_names()
Gregory P. Smithad577b92015-05-22 16:18:14 -0700243 if output_type is bytes:
244 names = map(_os.fsencode, names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000245
Guido van Rossum805365e2007-05-07 22:24:25 +0000246 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000247 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000248 file = _os.path.join(dir, pre + name + suf)
Steve Dower60419a72019-06-24 08:42:54 -0700249 _sys.audit("tempfile.mkstemp", file)
Guido van Rossum0e548712002-08-09 16:14:33 +0000250 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000251 fd = _os.open(file, flags, 0o600)
Florent Xicluna68f71a32011-10-28 16:06:23 +0200252 except FileExistsError:
253 continue # try again
Eli Benderskyf315df32013-09-06 06:11:19 -0700254 except PermissionError:
255 # This exception is thrown when a directory with the chosen name
256 # already exists on windows.
Serhiy Storchaka5d6b7b12015-05-20 00:11:48 +0300257 if (_os.name == 'nt' and _os.path.isdir(dir) and
258 _os.access(dir, _os.W_OK)):
Eli Benderskyf315df32013-09-06 06:11:19 -0700259 continue
260 else:
261 raise
Gregory P. Smithad577b92015-05-22 16:18:14 -0700262 return (fd, _os.path.abspath(file))
Guido van Rossum0e548712002-08-09 16:14:33 +0000263
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200264 raise FileExistsError(_errno.EEXIST,
265 "No usable temporary file name found")
Tim Petersa0d55de2002-08-09 18:01:01 +0000266
Guido van Rossum0e548712002-08-09 16:14:33 +0000267
268# User visible interfaces.
Guido van Rossumb0e57181998-10-14 20:27:05 +0000269
Guido van Rossum41f95031992-03-31 19:02:01 +0000270def gettempprefix():
Gregory P. Smithad577b92015-05-22 16:18:14 -0700271 """The default prefix for temporary directories."""
Guido van Rossum0e548712002-08-09 16:14:33 +0000272 return template
Tim Peters9fadfb02001-01-13 03:04:02 +0000273
Gregory P. Smithad577b92015-05-22 16:18:14 -0700274def gettempprefixb():
275 """The default prefix for temporary directories as bytes."""
276 return _os.fsencode(gettempprefix())
277
Guido van Rossume888cdc2002-08-17 14:50:24 +0000278tempdir = None
279
Guido van Rossum0e548712002-08-09 16:14:33 +0000280def gettempdir():
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000281 """Accessor for tempfile.tempdir."""
Guido van Rossume888cdc2002-08-17 14:50:24 +0000282 global tempdir
283 if tempdir is None:
284 _once_lock.acquire()
285 try:
286 if tempdir is None:
287 tempdir = _get_default_tempdir()
288 finally:
289 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000290 return tempdir
291
Gregory P. Smithad577b92015-05-22 16:18:14 -0700292def gettempdirb():
293 """A bytes version of tempfile.gettempdir()."""
294 return _os.fsencode(gettempdir())
295
296def mkstemp(suffix=None, prefix=None, dir=None, text=False):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000297 """User-callable function to create and return a unique temporary
Guido van Rossum0e548712002-08-09 16:14:33 +0000298 file. The return value is a pair (fd, name) where fd is the
299 file descriptor returned by os.open, and name is the filename.
300
Martin Panter9b566c32015-11-07 00:32:50 +0000301 If 'suffix' is not None, the file name will end with that suffix,
Guido van Rossum0e548712002-08-09 16:14:33 +0000302 otherwise there will be no suffix.
303
Martin Panter9b566c32015-11-07 00:32:50 +0000304 If 'prefix' is not None, the file name will begin with that prefix,
Guido van Rossum0e548712002-08-09 16:14:33 +0000305 otherwise a default prefix is used.
306
Martin Panter9b566c32015-11-07 00:32:50 +0000307 If 'dir' is not None, the file will be created in that directory,
Guido van Rossum0e548712002-08-09 16:14:33 +0000308 otherwise a default directory is used.
309
Tim Peters04490bf2002-08-14 15:41:26 +0000310 If 'text' is specified and true, the file is opened in text
311 mode. Else (the default) the file is opened in binary mode. On
312 some operating systems, this makes no difference.
Guido van Rossum0e548712002-08-09 16:14:33 +0000313
Martin Panter9b566c32015-11-07 00:32:50 +0000314 If any of 'suffix', 'prefix' and 'dir' are not None, they must be the
315 same type. If they are bytes, the returned name will be bytes; str
316 otherwise.
Gregory P. Smithad577b92015-05-22 16:18:14 -0700317
Guido van Rossum0e548712002-08-09 16:14:33 +0000318 The file is readable and writable only by the creating user ID.
319 If the operating system uses permission bits to indicate whether a
320 file is executable, the file is executable by no one. The file
321 descriptor is not inherited by children of this process.
322
323 Caller is responsible for deleting the file when done with it.
Tim Peters9fadfb02001-01-13 03:04:02 +0000324 """
325
Gregory P. Smithad577b92015-05-22 16:18:14 -0700326 prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
Guido van Rossume888cdc2002-08-17 14:50:24 +0000327
Tim Peters04490bf2002-08-14 15:41:26 +0000328 if text:
Guido van Rossum0e548712002-08-09 16:14:33 +0000329 flags = _text_openflags
Tim Peters04490bf2002-08-14 15:41:26 +0000330 else:
331 flags = _bin_openflags
Guido van Rossum0e548712002-08-09 16:14:33 +0000332
Gregory P. Smithad577b92015-05-22 16:18:14 -0700333 return _mkstemp_inner(dir, prefix, suffix, flags, output_type)
Guido van Rossumcff34541992-01-14 18:31:56 +0000334
Guido van Rossumeee94981991-11-12 15:38:08 +0000335
Gregory P. Smithad577b92015-05-22 16:18:14 -0700336def mkdtemp(suffix=None, prefix=None, dir=None):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000337 """User-callable function to create and return a unique temporary
Guido van Rossum0e548712002-08-09 16:14:33 +0000338 directory. The return value is the pathname of the directory.
339
Tim Peters04490bf2002-08-14 15:41:26 +0000340 Arguments are as for mkstemp, except that the 'text' argument is
Guido van Rossum0e548712002-08-09 16:14:33 +0000341 not accepted.
342
343 The directory is readable, writable, and searchable only by the
344 creating user.
345
346 Caller is responsible for deleting the directory when done with it.
347 """
348
Gregory P. Smithad577b92015-05-22 16:18:14 -0700349 prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
Guido van Rossume888cdc2002-08-17 14:50:24 +0000350
Guido van Rossum0e548712002-08-09 16:14:33 +0000351 names = _get_candidate_names()
Gregory P. Smithad577b92015-05-22 16:18:14 -0700352 if output_type is bytes:
353 names = map(_os.fsencode, names)
Tim Petersa0d55de2002-08-09 18:01:01 +0000354
Guido van Rossum805365e2007-05-07 22:24:25 +0000355 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000356 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000357 file = _os.path.join(dir, prefix + name + suffix)
Steve Dower60419a72019-06-24 08:42:54 -0700358 _sys.audit("tempfile.mkdtemp", file)
Guido van Rossum0e548712002-08-09 16:14:33 +0000359 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000360 _os.mkdir(file, 0o700)
Florent Xicluna68f71a32011-10-28 16:06:23 +0200361 except FileExistsError:
362 continue # try again
Serhiy Storchaka5d6b7b12015-05-20 00:11:48 +0300363 except PermissionError:
364 # This exception is thrown when a directory with the chosen name
365 # already exists on windows.
366 if (_os.name == 'nt' and _os.path.isdir(dir) and
367 _os.access(dir, _os.W_OK)):
368 continue
369 else:
370 raise
Gregory P. Smithad577b92015-05-22 16:18:14 -0700371 return file
Guido van Rossum0e548712002-08-09 16:14:33 +0000372
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200373 raise FileExistsError(_errno.EEXIST,
374 "No usable temporary directory name found")
Guido van Rossum0e548712002-08-09 16:14:33 +0000375
Guido van Rossume888cdc2002-08-17 14:50:24 +0000376def mktemp(suffix="", prefix=template, dir=None):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000377 """User-callable function to return a unique temporary file name. The
Guido van Rossum0e548712002-08-09 16:14:33 +0000378 file is not created.
379
Martin Panter9b566c32015-11-07 00:32:50 +0000380 Arguments are similar to mkstemp, except that the 'text' argument is
381 not accepted, and suffix=None, prefix=None and bytes file names are not
382 supported.
Guido van Rossum0e548712002-08-09 16:14:33 +0000383
Gregory P. Smithad577b92015-05-22 16:18:14 -0700384 THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may
385 refer to a file that did not exist at some point, but by the time
Guido van Rossum0e548712002-08-09 16:14:33 +0000386 you get around to creating it, someone else may have beaten you to
387 the punch.
388 """
389
Guido van Rossum44f602d2002-11-22 15:56:29 +0000390## from warnings import warn as _warn
391## _warn("mktemp is a potential security risk to your program",
392## RuntimeWarning, stacklevel=2)
Guido van Rossum0e548712002-08-09 16:14:33 +0000393
Guido van Rossume888cdc2002-08-17 14:50:24 +0000394 if dir is None:
395 dir = gettempdir()
396
Guido van Rossum0e548712002-08-09 16:14:33 +0000397 names = _get_candidate_names()
Guido van Rossum805365e2007-05-07 22:24:25 +0000398 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000399 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000400 file = _os.path.join(dir, prefix + name + suffix)
Guido van Rossumb256159392003-11-10 02:16:36 +0000401 if not _exists(file):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000402 return file
Guido van Rossumca549821997-08-12 18:00:12 +0000403
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200404 raise FileExistsError(_errno.EEXIST,
405 "No usable temporary filename found")
Guido van Rossumca549821997-08-12 18:00:12 +0000406
Christian Heimes3ecfea712008-02-09 20:51:34 +0000407
Antoine Pitrou17c93262013-12-21 22:14:56 +0100408class _TemporaryFileCloser:
409 """A separate object allowing proper closing of a temporary file's
410 underlying file object, without adding a __del__ method to the
411 temporary file."""
Tim Petersa255a722001-12-18 22:32:40 +0000412
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200413 file = None # Set here since __del__ checks it
Serhiy Storchaka99e033b2014-01-27 11:18:27 +0200414 close_called = False
415
Guido van Rossumd8faa362007-04-27 19:54:29 +0000416 def __init__(self, file, name, delete=True):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000417 self.file = file
Guido van Rossum0e548712002-08-09 16:14:33 +0000418 self.name = name
Guido van Rossumd8faa362007-04-27 19:54:29 +0000419 self.delete = delete
Guido van Rossumca549821997-08-12 18:00:12 +0000420
Guido van Rossum0e548712002-08-09 16:14:33 +0000421 # NT provides delete-on-close as a primitive, so we don't need
422 # the wrapper to do anything special. We still use it so that
423 # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
424 if _os.name != 'nt':
Guido van Rossum0e548712002-08-09 16:14:33 +0000425 # Cache the unlinker so we don't get spurious errors at
426 # shutdown when the module-level "os" is None'd out. Note
427 # that this must be referenced as self.unlink, because the
428 # name TemporaryFileWrapper may also get None'd out before
429 # __del__ is called.
Tim Peters1baa22a2001-01-12 10:02:46 +0000430
Serhiy Storchaka99e033b2014-01-27 11:18:27 +0200431 def close(self, unlink=_os.unlink):
432 if not self.close_called and self.file is not None:
Tim Peters6ef966e2002-11-21 15:48:33 +0000433 self.close_called = True
Serhiy Storchaka7e7a3db2015-04-10 13:24:41 +0300434 try:
435 self.file.close()
436 finally:
437 if self.delete:
438 unlink(self.name)
Tim Peters1baa22a2001-01-12 10:02:46 +0000439
Antoine Pitrou17c93262013-12-21 22:14:56 +0100440 # Need to ensure the file is deleted on __del__
Guido van Rossum0e548712002-08-09 16:14:33 +0000441 def __del__(self):
442 self.close()
Tim Peters1baa22a2001-01-12 10:02:46 +0000443
Benjamin Peterson98d23f22009-06-30 22:27:25 +0000444 else:
Antoine Pitrou17c93262013-12-21 22:14:56 +0100445 def close(self):
446 if not self.close_called:
447 self.close_called = True
448 self.file.close()
449
450
451class _TemporaryFileWrapper:
452 """Temporary file wrapper
453
454 This class provides a wrapper around files opened for
455 temporary use. In particular, it seeks to automatically
456 remove the file when it is no longer needed.
457 """
458
459 def __init__(self, file, name, delete=True):
460 self.file = file
461 self.name = name
462 self.delete = delete
463 self._closer = _TemporaryFileCloser(file, name, delete)
464
465 def __getattr__(self, name):
466 # Attribute lookups are delegated to the underlying file
467 # and cached for non-numeric results
468 # (i.e. methods are cached, closed and friends are not)
469 file = self.__dict__['file']
470 a = getattr(file, name)
471 if hasattr(a, '__call__'):
472 func = a
473 @_functools.wraps(func)
474 def func_wrapper(*args, **kwargs):
475 return func(*args, **kwargs)
476 # Avoid closing the file as long as the wrapper is alive,
477 # see issue #18879.
478 func_wrapper._closer = self._closer
479 a = func_wrapper
480 if not isinstance(a, int):
481 setattr(self, name, a)
482 return a
483
484 # The underlying __enter__ method returns the wrong object
485 # (self.file) so override it to return the wrapper
486 def __enter__(self):
487 self.file.__enter__()
488 return self
489
490 # Need to trap __exit__ as well to ensure the file gets
491 # deleted when used in a with statement
492 def __exit__(self, exc, value, tb):
493 result = self.file.__exit__(exc, value, tb)
494 self.close()
495 return result
496
497 def close(self):
498 """
499 Close the temporary file, possibly deleting it.
500 """
501 self._closer.close()
502
503 # iter() doesn't use __getattr__ to find the __iter__ method
504 def __iter__(self):
Serhiy Storchakad83b7c22015-03-20 16:11:20 +0200505 # Don't return iter(self.file), but yield from it to avoid closing
R David Murray75ed90a2015-03-22 12:33:46 -0400506 # file as long as it's being used as iterator (see issue #23700). We
507 # can't use 'yield from' here because iter(file) returns the file
508 # object itself, which has a close method, and thus the file would get
509 # closed when the generator is finalized, due to PEP380 semantics.
Serhiy Storchakad83b7c22015-03-20 16:11:20 +0200510 for line in self.file:
511 yield line
Christian Heimes3ecfea712008-02-09 20:51:34 +0000512
513
Guido van Rossumf0c74162007-08-28 03:29:45 +0000514def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None,
Gregory P. Smithad577b92015-05-22 16:18:14 -0700515 newline=None, suffix=None, prefix=None,
sth825aab92018-05-23 07:07:01 +0200516 dir=None, delete=True, *, errors=None):
Guido van Rossum0e548712002-08-09 16:14:33 +0000517 """Create and return a temporary file.
518 Arguments:
519 'prefix', 'suffix', 'dir' -- as for mkstemp.
Guido van Rossumf0c74162007-08-28 03:29:45 +0000520 'mode' -- the mode argument to io.open (default "w+b").
521 'buffering' -- the buffer size argument to io.open (default -1).
522 'encoding' -- the encoding argument to io.open (default None)
523 'newline' -- the newline argument to io.open (default None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000524 'delete' -- whether the file is deleted on close (default True).
sth825aab92018-05-23 07:07:01 +0200525 'errors' -- the errors argument to io.open (default None)
Guido van Rossum0e548712002-08-09 16:14:33 +0000526 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000527
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000528 Returns an object with a file-like interface; the name of the file
Martin Panter1f0e1f32016-02-22 10:10:00 +0000529 is accessible as its 'name' attribute. The file will be automatically
530 deleted when it is closed unless the 'delete' argument is set to False.
Guido van Rossum0e548712002-08-09 16:14:33 +0000531 """
Tim Peters1baa22a2001-01-12 10:02:46 +0000532
Gregory P. Smithad577b92015-05-22 16:18:14 -0700533 prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
Guido van Rossume888cdc2002-08-17 14:50:24 +0000534
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000535 flags = _bin_openflags
Tim Peters1baa22a2001-01-12 10:02:46 +0000536
Guido van Rossum0e548712002-08-09 16:14:33 +0000537 # Setting O_TEMPORARY in the flags causes the OS to delete
538 # the file when it is closed. This is only supported by Windows.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000539 if _os.name == 'nt' and delete:
Guido van Rossum0e548712002-08-09 16:14:33 +0000540 flags |= _os.O_TEMPORARY
Tim Peters1baa22a2001-01-12 10:02:46 +0000541
Gregory P. Smithad577b92015-05-22 16:18:14 -0700542 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type)
Victor Stinner1f99f9d2014-03-25 09:18:04 +0100543 try:
544 file = _io.open(fd, mode, buffering=buffering,
sth825aab92018-05-23 07:07:01 +0200545 newline=newline, encoding=encoding, errors=errors)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000546
Victor Stinner1f99f9d2014-03-25 09:18:04 +0100547 return _TemporaryFileWrapper(file, name, delete)
Martin Panter7869a222016-02-28 05:22:20 +0000548 except BaseException:
549 _os.unlink(name)
Victor Stinner1f99f9d2014-03-25 09:18:04 +0100550 _os.close(fd)
551 raise
Guido van Rossum0e548712002-08-09 16:14:33 +0000552
Steve Dower60419a72019-06-24 08:42:54 -0700553if _os.name != 'posix' or _sys.platform == 'cygwin':
Jason Tishler80c02af2002-08-14 15:10:09 +0000554 # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
555 # while it is open.
Guido van Rossum0e548712002-08-09 16:14:33 +0000556 TemporaryFile = NamedTemporaryFile
Tim Peters1baa22a2001-01-12 10:02:46 +0000557
558else:
Victor Stinnerd967fc92014-06-05 14:27:45 +0200559 # Is the O_TMPFILE flag available and does it work?
560 # The flag is set to False if os.open(dir, os.O_TMPFILE) raises an
561 # IsADirectoryError exception
562 _O_TMPFILE_WORKS = hasattr(_os, 'O_TMPFILE')
563
Guido van Rossumf0c74162007-08-28 03:29:45 +0000564 def TemporaryFile(mode='w+b', buffering=-1, encoding=None,
Gregory P. Smithad577b92015-05-22 16:18:14 -0700565 newline=None, suffix=None, prefix=None,
sth825aab92018-05-23 07:07:01 +0200566 dir=None, *, errors=None):
Guido van Rossum0e548712002-08-09 16:14:33 +0000567 """Create and return a temporary file.
568 Arguments:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000569 'prefix', 'suffix', 'dir' -- as for mkstemp.
Guido van Rossumf0c74162007-08-28 03:29:45 +0000570 'mode' -- the mode argument to io.open (default "w+b").
571 'buffering' -- the buffer size argument to io.open (default -1).
572 'encoding' -- the encoding argument to io.open (default None)
573 'newline' -- the newline argument to io.open (default None)
sth825aab92018-05-23 07:07:01 +0200574 'errors' -- the errors argument to io.open (default None)
Guido van Rossum0e548712002-08-09 16:14:33 +0000575 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000576
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000577 Returns an object with a file-like interface. The file has no
578 name, and will cease to exist when it is closed.
Guido van Rossum0e548712002-08-09 16:14:33 +0000579 """
Victor Stinnerd967fc92014-06-05 14:27:45 +0200580 global _O_TMPFILE_WORKS
Guido van Rossum0e548712002-08-09 16:14:33 +0000581
Gregory P. Smithad577b92015-05-22 16:18:14 -0700582 prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
Guido van Rossume888cdc2002-08-17 14:50:24 +0000583
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000584 flags = _bin_openflags
Victor Stinnerd967fc92014-06-05 14:27:45 +0200585 if _O_TMPFILE_WORKS:
586 try:
587 flags2 = (flags | _os.O_TMPFILE) & ~_os.O_CREAT
588 fd = _os.open(dir, flags2, 0o600)
589 except IsADirectoryError:
Victor Stinner9aba8c82015-10-21 00:15:08 +0200590 # Linux kernel older than 3.11 ignores the O_TMPFILE flag:
591 # O_TMPFILE is read as O_DIRECTORY. Trying to open a directory
592 # with O_RDWR|O_DIRECTORY fails with IsADirectoryError, a
593 # directory cannot be open to write. Set flag to False to not
594 # try again.
Victor Stinnerd967fc92014-06-05 14:27:45 +0200595 _O_TMPFILE_WORKS = False
596 except OSError:
597 # The filesystem of the directory does not support O_TMPFILE.
598 # For example, OSError(95, 'Operation not supported').
Victor Stinner9aba8c82015-10-21 00:15:08 +0200599 #
600 # On Linux kernel older than 3.11, trying to open a regular
601 # file (or a symbolic link to a regular file) with O_TMPFILE
602 # fails with NotADirectoryError, because O_TMPFILE is read as
603 # O_DIRECTORY.
Victor Stinnerd967fc92014-06-05 14:27:45 +0200604 pass
605 else:
606 try:
607 return _io.open(fd, mode, buffering=buffering,
sth825aab92018-05-23 07:07:01 +0200608 newline=newline, encoding=encoding,
609 errors=errors)
Victor Stinnerd967fc92014-06-05 14:27:45 +0200610 except:
611 _os.close(fd)
612 raise
613 # Fallback to _mkstemp_inner().
Guido van Rossum0e548712002-08-09 16:14:33 +0000614
Gregory P. Smithad577b92015-05-22 16:18:14 -0700615 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type)
Guido van Rossum0e548712002-08-09 16:14:33 +0000616 try:
617 _os.unlink(name)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000618 return _io.open(fd, mode, buffering=buffering,
sth825aab92018-05-23 07:07:01 +0200619 newline=newline, encoding=encoding, errors=errors)
Guido van Rossum0e548712002-08-09 16:14:33 +0000620 except:
621 _os.close(fd)
622 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +0000623
624class SpooledTemporaryFile:
Serhiy Storchaka4f169a72013-02-09 11:46:42 +0200625 """Temporary file wrapper, specialized to switch from BytesIO
626 or StringIO to a real file when it exceeds a certain size or
Guido van Rossumd8faa362007-04-27 19:54:29 +0000627 when a fileno is needed.
628 """
629 _rolled = False
630
Guido van Rossumf0c74162007-08-28 03:29:45 +0000631 def __init__(self, max_size=0, mode='w+b', buffering=-1,
632 encoding=None, newline=None,
sth825aab92018-05-23 07:07:01 +0200633 suffix=None, prefix=None, dir=None, *, errors=None):
Guido van Rossum9a634702007-07-09 10:24:45 +0000634 if 'b' in mode:
635 self._file = _io.BytesIO()
636 else:
Inada Naokiea9835c2019-11-27 22:22:06 +0900637 self._file = _io.TextIOWrapper(_io.BytesIO(),
638 encoding=encoding, errors=errors,
639 newline=newline)
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
Guido van Rossum48b069a2020-04-07 09:50:06 -0700647 __class_getitem__ = classmethod(_types.GenericAlias)
Batuhan Taşkaya09c482f2019-12-30 19:08:08 +0300648
Guido van Rossumd8faa362007-04-27 19:54:29 +0000649 def _check(self, file):
650 if self._rolled: return
651 max_size = self._max_size
652 if max_size and file.tell() > max_size:
653 self.rollover()
654
655 def rollover(self):
656 if self._rolled: return
657 file = self._file
Guido van Rossumf0c74162007-08-28 03:29:45 +0000658 newfile = self._file = TemporaryFile(**self._TemporaryFileArgs)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000659 del self._TemporaryFileArgs
660
Inada Naokiea9835c2019-11-27 22:22:06 +0900661 pos = file.tell()
662 if hasattr(newfile, 'buffer'):
663 newfile.buffer.write(file.detach().getvalue())
664 else:
665 newfile.write(file.getvalue())
666 newfile.seek(pos, 0)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000667
668 self._rolled = True
669
Christian Heimes3ecfea712008-02-09 20:51:34 +0000670 # The method caching trick from NamedTemporaryFile
671 # won't work here, because _file may change from a
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300672 # BytesIO/StringIO instance to a real file. So we list
Christian Heimes3ecfea712008-02-09 20:51:34 +0000673 # all the methods directly.
674
675 # Context management protocol
676 def __enter__(self):
677 if self._file.closed:
678 raise ValueError("Cannot enter context with closed file")
679 return self
680
681 def __exit__(self, exc, value, tb):
682 self._file.close()
683
Guido van Rossumd8faa362007-04-27 19:54:29 +0000684 # file protocol
685 def __iter__(self):
686 return self._file.__iter__()
687
688 def close(self):
689 self._file.close()
690
691 @property
692 def closed(self):
693 return self._file.closed
694
695 @property
696 def encoding(self):
sth825aab92018-05-23 07:07:01 +0200697 return self._file.encoding
698
699 @property
700 def errors(self):
701 return self._file.errors
Guido van Rossumd8faa362007-04-27 19:54:29 +0000702
703 def fileno(self):
704 self.rollover()
705 return self._file.fileno()
706
707 def flush(self):
708 self._file.flush()
709
710 def isatty(self):
711 return self._file.isatty()
712
713 @property
714 def mode(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200715 try:
716 return self._file.mode
717 except AttributeError:
718 return self._TemporaryFileArgs['mode']
Guido van Rossumd8faa362007-04-27 19:54:29 +0000719
720 @property
721 def name(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200722 try:
723 return self._file.name
724 except AttributeError:
725 return None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000726
727 @property
728 def newlines(self):
sth825aab92018-05-23 07:07:01 +0200729 return self._file.newlines
Guido van Rossumd8faa362007-04-27 19:54:29 +0000730
731 def read(self, *args):
732 return self._file.read(*args)
733
734 def readline(self, *args):
735 return self._file.readline(*args)
736
737 def readlines(self, *args):
738 return self._file.readlines(*args)
739
740 def seek(self, *args):
Inada Naoki485e7152020-04-17 15:56:35 +0900741 return self._file.seek(*args)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000742
Guido van Rossumd8faa362007-04-27 19:54:29 +0000743 def tell(self):
744 return self._file.tell()
745
Antoine Pitrou0e86a582011-11-25 18:03:09 +0100746 def truncate(self, size=None):
747 if size is None:
748 self._file.truncate()
749 else:
750 if size > self._max_size:
751 self.rollover()
752 self._file.truncate(size)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000753
754 def write(self, s):
755 file = self._file
756 rv = file.write(s)
757 self._check(file)
758 return rv
759
760 def writelines(self, iterable):
761 file = self._file
762 rv = file.writelines(iterable)
763 self._check(file)
764 return rv
765
Nick Coghlan543af752010-10-24 11:23:25 +0000766
767class TemporaryDirectory(object):
768 """Create and return a temporary directory. This has the same
769 behavior as mkdtemp but can be used as a context manager. For
770 example:
771
772 with TemporaryDirectory() as tmpdir:
773 ...
774
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300775 Upon exiting the context, the directory and everything contained
Nick Coghlan543af752010-10-24 11:23:25 +0000776 in it are removed.
777 """
778
Gregory P. Smithad577b92015-05-22 16:18:14 -0700779 def __init__(self, suffix=None, prefix=None, dir=None):
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000780 self.name = mkdtemp(suffix, prefix, dir)
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200781 self._finalizer = _weakref.finalize(
782 self, self._cleanup, self.name,
783 warn_message="Implicitly cleaning up {!r}".format(self))
784
785 @classmethod
Serhiy Storchakae9b51c02019-05-31 11:30:37 +0300786 def _rmtree(cls, name):
787 def onerror(func, path, exc_info):
788 if issubclass(exc_info[0], PermissionError):
789 def resetperms(path):
790 try:
791 _os.chflags(path, 0)
792 except AttributeError:
793 pass
794 _os.chmod(path, 0o700)
795
796 try:
797 if path != name:
798 resetperms(_os.path.dirname(path))
799 resetperms(path)
800
801 try:
802 _os.unlink(path)
803 # PermissionError is raised on FreeBSD for directories
804 except (IsADirectoryError, PermissionError):
805 cls._rmtree(path)
806 except FileNotFoundError:
807 pass
808 elif issubclass(exc_info[0], FileNotFoundError):
809 pass
810 else:
811 raise
812
813 _shutil.rmtree(name, onerror=onerror)
814
815 @classmethod
Serhiy Storchaka5e193ac2014-09-24 13:26:25 +0300816 def _cleanup(cls, name, warn_message):
Serhiy Storchakae9b51c02019-05-31 11:30:37 +0300817 cls._rmtree(name)
Serhiy Storchaka5e193ac2014-09-24 13:26:25 +0300818 _warnings.warn(warn_message, ResourceWarning)
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200819
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000820 def __repr__(self):
821 return "<{} {!r}>".format(self.__class__.__name__, self.name)
Nick Coghlan543af752010-10-24 11:23:25 +0000822
823 def __enter__(self):
824 return self.name
825
Nick Coghlan543af752010-10-24 11:23:25 +0000826 def __exit__(self, exc, value, tb):
827 self.cleanup()
828
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200829 def cleanup(self):
Serhiy Storchaka5e193ac2014-09-24 13:26:25 +0300830 if self._finalizer.detach():
Serhiy Storchakae9b51c02019-05-31 11:30:37 +0300831 self._rmtree(self.name)
Batuhan Taşkaya03615562020-04-10 17:46:36 +0300832
833 __class_getitem__ = classmethod(_types.GenericAlias)