blob: e6fb3c8e9ad856d83b5ac66365479681cf8a4d38 [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
Serhiy Storchakaa28632b2014-01-27 11:21:54 +020046import weakref as _weakref
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020047import _thread
Guido van Rossuma0934242002-12-30 22:36:09 +000048_allocate_lock = _thread.allocate_lock
Guido van Rossum0e548712002-08-09 16:14:33 +000049
50_text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL
Tim Petersa0d55de2002-08-09 18:01:01 +000051if hasattr(_os, 'O_NOFOLLOW'):
52 _text_openflags |= _os.O_NOFOLLOW
Guido van Rossum0e548712002-08-09 16:14:33 +000053
54_bin_openflags = _text_openflags
Tim Petersa0d55de2002-08-09 18:01:01 +000055if hasattr(_os, 'O_BINARY'):
56 _bin_openflags |= _os.O_BINARY
Guido van Rossum0e548712002-08-09 16:14:33 +000057
58if hasattr(_os, 'TMP_MAX'):
59 TMP_MAX = _os.TMP_MAX
60else:
61 TMP_MAX = 10000
62
Gregory P. Smithad577b92015-05-22 16:18:14 -070063# This variable _was_ unused for legacy reasons, see issue 10354.
64# But as of 3.5 we actually use it at runtime so changing it would
65# have a possibly desirable side effect... But we do not want to support
66# that as an API. It is undocumented on purpose. Do not depend on this.
Tim Petersbd7b4c72002-08-13 23:33:56 +000067template = "tmp"
Guido van Rossum0e548712002-08-09 16:14:33 +000068
Guido van Rossum0e548712002-08-09 16:14:33 +000069# Internal routines.
70
71_once_lock = _allocate_lock()
72
Guido van Rossumb256159392003-11-10 02:16:36 +000073if hasattr(_os, "lstat"):
74 _stat = _os.lstat
75elif hasattr(_os, "stat"):
76 _stat = _os.stat
77else:
Florent Xicluna68f71a32011-10-28 16:06:23 +020078 # Fallback. All we need is something that raises OSError if the
Guido van Rossumb256159392003-11-10 02:16:36 +000079 # file doesn't exist.
80 def _stat(fn):
Victor Stinnerdaf45552013-08-28 00:53:59 +020081 fd = _os.open(fn, _os.O_RDONLY)
Victor Stinner69b1e262014-03-20 08:50:52 +010082 _os.close(fd)
Guido van Rossumb256159392003-11-10 02:16:36 +000083
84def _exists(fn):
85 try:
86 _stat(fn)
Florent Xicluna68f71a32011-10-28 16:06:23 +020087 except OSError:
Guido van Rossumb256159392003-11-10 02:16:36 +000088 return False
89 else:
90 return True
91
Gregory P. Smithad577b92015-05-22 16:18:14 -070092
93def _infer_return_type(*args):
94 """Look at the type of all args and divine their implied return type."""
95 return_type = None
96 for arg in args:
97 if arg is None:
98 continue
99 if isinstance(arg, bytes):
100 if return_type is str:
101 raise TypeError("Can't mix bytes and non-bytes in "
102 "path components.")
103 return_type = bytes
104 else:
105 if return_type is bytes:
106 raise TypeError("Can't mix bytes and non-bytes in "
107 "path components.")
108 return_type = str
109 if return_type is None:
110 return str # tempfile APIs return a str by default.
111 return return_type
112
113
114def _sanitize_params(prefix, suffix, dir):
115 """Common parameter processing for most APIs in this module."""
116 output_type = _infer_return_type(prefix, suffix, dir)
117 if suffix is None:
118 suffix = output_type()
119 if prefix is None:
120 if output_type is str:
121 prefix = template
122 else:
123 prefix = _os.fsencode(template)
124 if dir is None:
125 if output_type is str:
126 dir = gettempdir()
127 else:
128 dir = gettempdirb()
129 return prefix, suffix, dir, output_type
130
131
Victor Stinner1e62bf12017-04-19 22:59:51 +0200132class _RandomNameSequence:
133 """An instance of _RandomNameSequence generates an endless
134 sequence of unpredictable strings which can safely be incorporated
Wolfgang Maier9c463ec2018-04-09 02:42:39 +0200135 into file names. Each string is eight characters long. Multiple
Victor Stinner1e62bf12017-04-19 22:59:51 +0200136 threads can safely use the same instance at the same time.
137
138 _RandomNameSequence is an iterator."""
Guido van Rossum0e548712002-08-09 16:14:33 +0000139
Raymond Hettinger572895b2010-11-09 03:43:58 +0000140 characters = "abcdefghijklmnopqrstuvwxyz0123456789_"
Victor Stinner1e62bf12017-04-19 22:59:51 +0200141
142 @property
143 def rng(self):
Antoine Pitrou4558bad2011-11-25 21:28:15 +0100144 cur_pid = _os.getpid()
Victor Stinner1e62bf12017-04-19 22:59:51 +0200145 if cur_pid != getattr(self, '_rng_pid', None):
146 self._rng = _Random()
147 self._rng_pid = cur_pid
148 return self._rng
149
150 def __iter__(self):
151 return self
152
153 def __next__(self):
154 c = self.characters
155 choose = self.rng.choice
156 letters = [choose(c) for dummy in range(8)]
157 return ''.join(letters)
Guido van Rossum0e548712002-08-09 16:14:33 +0000158
159def _candidate_tempdir_list():
160 """Generate a list of candidate temporary directories which
161 _get_default_tempdir will try."""
162
163 dirlist = []
164
165 # First, try the environment.
166 for envname in 'TMPDIR', 'TEMP', 'TMP':
167 dirname = _os.getenv(envname)
168 if dirname: dirlist.append(dirname)
169
170 # Failing that, try OS-specific locations.
Alexandre Vassalottieca20b62008-05-16 02:54:33 +0000171 if _os.name == 'nt':
Steve Dowere5f41d22018-05-16 17:50:29 -0400172 dirlist.extend([ _os.path.expanduser(r'~\AppData\Local\Temp'),
173 _os.path.expandvars(r'%SYSTEMROOT%\Temp'),
174 r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
Guido van Rossum0e548712002-08-09 16:14:33 +0000175 else:
176 dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
177
178 # As a last resort, the current directory.
179 try:
180 dirlist.append(_os.getcwd())
Florent Xicluna68f71a32011-10-28 16:06:23 +0200181 except (AttributeError, OSError):
Guido van Rossum0e548712002-08-09 16:14:33 +0000182 dirlist.append(_os.curdir)
183
184 return dirlist
Tim Petersa0d55de2002-08-09 18:01:01 +0000185
Guido van Rossum0e548712002-08-09 16:14:33 +0000186def _get_default_tempdir():
187 """Calculate the default directory to use for temporary files.
Guido van Rossume888cdc2002-08-17 14:50:24 +0000188 This routine should be called exactly once.
Guido van Rossum0e548712002-08-09 16:14:33 +0000189
190 We determine whether or not a candidate temp dir is usable by
191 trying to create and write to a file in that directory. If this
192 is successful, the test file is deleted. To prevent denial of
193 service, the name of the test file must be randomized."""
194
195 namer = _RandomNameSequence()
196 dirlist = _candidate_tempdir_list()
Guido van Rossum0e548712002-08-09 16:14:33 +0000197
198 for dir in dirlist:
199 if dir != _os.curdir:
Tim Golden6d09f092013-10-25 18:38:16 +0100200 dir = _os.path.abspath(dir)
Guido van Rossum0e548712002-08-09 16:14:33 +0000201 # Try only a few names per directory.
Guido van Rossum805365e2007-05-07 22:24:25 +0000202 for seq in range(100):
Georg Brandla18af4e2007-04-21 15:47:16 +0000203 name = next(namer)
Guido van Rossum0e548712002-08-09 16:14:33 +0000204 filename = _os.path.join(dir, name)
205 try:
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000206 fd = _os.open(filename, _bin_openflags, 0o600)
Serhiy Storchakaf6b361e2013-02-13 00:35:30 +0200207 try:
208 try:
Serhiy Storchaka76a2ed12013-02-13 00:59:26 +0200209 with _io.open(fd, 'wb', closefd=False) as fp:
210 fp.write(b'blat')
Serhiy Storchakaf6b361e2013-02-13 00:35:30 +0200211 finally:
212 _os.close(fd)
213 finally:
214 _os.unlink(filename)
Guido van Rossum0e548712002-08-09 16:14:33 +0000215 return dir
Florent Xicluna68f71a32011-10-28 16:06:23 +0200216 except FileExistsError:
Guido van Rossum0e548712002-08-09 16:14:33 +0000217 pass
Serhiy Storchaka5d6b7b12015-05-20 00:11:48 +0300218 except PermissionError:
219 # This exception is thrown when a directory with the chosen name
220 # already exists on windows.
221 if (_os.name == 'nt' and _os.path.isdir(dir) and
222 _os.access(dir, _os.W_OK)):
223 continue
224 break # no point trying more names in this directory
Florent Xicluna68f71a32011-10-28 16:06:23 +0200225 except OSError:
226 break # no point trying more names in this directory
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200227 raise FileNotFoundError(_errno.ENOENT,
228 "No usable temporary directory found in %s" %
229 dirlist)
Guido van Rossum0e548712002-08-09 16:14:33 +0000230
Guido van Rossume888cdc2002-08-17 14:50:24 +0000231_name_sequence = None
232
Guido van Rossum0e548712002-08-09 16:14:33 +0000233def _get_candidate_names():
234 """Common setup sequence for all user-callable interfaces."""
235
Guido van Rossume888cdc2002-08-17 14:50:24 +0000236 global _name_sequence
237 if _name_sequence is None:
238 _once_lock.acquire()
239 try:
240 if _name_sequence is None:
241 _name_sequence = _RandomNameSequence()
242 finally:
243 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000244 return _name_sequence
Guido van Rossum41f95031992-03-31 19:02:01 +0000245
246
Gregory P. Smithad577b92015-05-22 16:18:14 -0700247def _mkstemp_inner(dir, pre, suf, flags, output_type):
Guido van Rossum0e548712002-08-09 16:14:33 +0000248 """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
Tim Peters9fadfb02001-01-13 03:04:02 +0000249
Guido van Rossum0e548712002-08-09 16:14:33 +0000250 names = _get_candidate_names()
Gregory P. Smithad577b92015-05-22 16:18:14 -0700251 if output_type is bytes:
252 names = map(_os.fsencode, names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000253
Guido van Rossum805365e2007-05-07 22:24:25 +0000254 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000255 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000256 file = _os.path.join(dir, pre + name + suf)
257 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000258 fd = _os.open(file, flags, 0o600)
Florent Xicluna68f71a32011-10-28 16:06:23 +0200259 except FileExistsError:
260 continue # try again
Eli Benderskyf315df32013-09-06 06:11:19 -0700261 except PermissionError:
262 # This exception is thrown when a directory with the chosen name
263 # already exists on windows.
Serhiy Storchaka5d6b7b12015-05-20 00:11:48 +0300264 if (_os.name == 'nt' and _os.path.isdir(dir) and
265 _os.access(dir, _os.W_OK)):
Eli Benderskyf315df32013-09-06 06:11:19 -0700266 continue
267 else:
268 raise
Gregory P. Smithad577b92015-05-22 16:18:14 -0700269 return (fd, _os.path.abspath(file))
Guido van Rossum0e548712002-08-09 16:14:33 +0000270
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200271 raise FileExistsError(_errno.EEXIST,
272 "No usable temporary file name found")
Tim Petersa0d55de2002-08-09 18:01:01 +0000273
Guido van Rossum0e548712002-08-09 16:14:33 +0000274
275# User visible interfaces.
Guido van Rossumb0e57181998-10-14 20:27:05 +0000276
Guido van Rossum41f95031992-03-31 19:02:01 +0000277def gettempprefix():
Gregory P. Smithad577b92015-05-22 16:18:14 -0700278 """The default prefix for temporary directories."""
Guido van Rossum0e548712002-08-09 16:14:33 +0000279 return template
Tim Peters9fadfb02001-01-13 03:04:02 +0000280
Gregory P. Smithad577b92015-05-22 16:18:14 -0700281def gettempprefixb():
282 """The default prefix for temporary directories as bytes."""
283 return _os.fsencode(gettempprefix())
284
Guido van Rossume888cdc2002-08-17 14:50:24 +0000285tempdir = None
286
Guido van Rossum0e548712002-08-09 16:14:33 +0000287def gettempdir():
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000288 """Accessor for tempfile.tempdir."""
Guido van Rossume888cdc2002-08-17 14:50:24 +0000289 global tempdir
290 if tempdir is None:
291 _once_lock.acquire()
292 try:
293 if tempdir is None:
294 tempdir = _get_default_tempdir()
295 finally:
296 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000297 return tempdir
298
Gregory P. Smithad577b92015-05-22 16:18:14 -0700299def gettempdirb():
300 """A bytes version of tempfile.gettempdir()."""
301 return _os.fsencode(gettempdir())
302
303def mkstemp(suffix=None, prefix=None, dir=None, text=False):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000304 """User-callable function to create and return a unique temporary
Guido van Rossum0e548712002-08-09 16:14:33 +0000305 file. The return value is a pair (fd, name) where fd is the
306 file descriptor returned by os.open, and name is the filename.
307
Martin Panter9b566c32015-11-07 00:32:50 +0000308 If 'suffix' is not None, the file name will end with that suffix,
Guido van Rossum0e548712002-08-09 16:14:33 +0000309 otherwise there will be no suffix.
310
Martin Panter9b566c32015-11-07 00:32:50 +0000311 If 'prefix' is not None, the file name will begin with that prefix,
Guido van Rossum0e548712002-08-09 16:14:33 +0000312 otherwise a default prefix is used.
313
Martin Panter9b566c32015-11-07 00:32:50 +0000314 If 'dir' is not None, the file will be created in that directory,
Guido van Rossum0e548712002-08-09 16:14:33 +0000315 otherwise a default directory is used.
316
Tim Peters04490bf2002-08-14 15:41:26 +0000317 If 'text' is specified and true, the file is opened in text
318 mode. Else (the default) the file is opened in binary mode. On
319 some operating systems, this makes no difference.
Guido van Rossum0e548712002-08-09 16:14:33 +0000320
Martin Panter9b566c32015-11-07 00:32:50 +0000321 If any of 'suffix', 'prefix' and 'dir' are not None, they must be the
322 same type. If they are bytes, the returned name will be bytes; str
323 otherwise.
Gregory P. Smithad577b92015-05-22 16:18:14 -0700324
Guido van Rossum0e548712002-08-09 16:14:33 +0000325 The file is readable and writable only by the creating user ID.
326 If the operating system uses permission bits to indicate whether a
327 file is executable, the file is executable by no one. The file
328 descriptor is not inherited by children of this process.
329
330 Caller is responsible for deleting the file when done with it.
Tim Peters9fadfb02001-01-13 03:04:02 +0000331 """
332
Gregory P. Smithad577b92015-05-22 16:18:14 -0700333 prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
Guido van Rossume888cdc2002-08-17 14:50:24 +0000334
Tim Peters04490bf2002-08-14 15:41:26 +0000335 if text:
Guido van Rossum0e548712002-08-09 16:14:33 +0000336 flags = _text_openflags
Tim Peters04490bf2002-08-14 15:41:26 +0000337 else:
338 flags = _bin_openflags
Guido van Rossum0e548712002-08-09 16:14:33 +0000339
Gregory P. Smithad577b92015-05-22 16:18:14 -0700340 return _mkstemp_inner(dir, prefix, suffix, flags, output_type)
Guido van Rossumcff34541992-01-14 18:31:56 +0000341
Guido van Rossumeee94981991-11-12 15:38:08 +0000342
Gregory P. Smithad577b92015-05-22 16:18:14 -0700343def mkdtemp(suffix=None, prefix=None, dir=None):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000344 """User-callable function to create and return a unique temporary
Guido van Rossum0e548712002-08-09 16:14:33 +0000345 directory. The return value is the pathname of the directory.
346
Tim Peters04490bf2002-08-14 15:41:26 +0000347 Arguments are as for mkstemp, except that the 'text' argument is
Guido van Rossum0e548712002-08-09 16:14:33 +0000348 not accepted.
349
350 The directory is readable, writable, and searchable only by the
351 creating user.
352
353 Caller is responsible for deleting the directory when done with it.
354 """
355
Gregory P. Smithad577b92015-05-22 16:18:14 -0700356 prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
Guido van Rossume888cdc2002-08-17 14:50:24 +0000357
Guido van Rossum0e548712002-08-09 16:14:33 +0000358 names = _get_candidate_names()
Gregory P. Smithad577b92015-05-22 16:18:14 -0700359 if output_type is bytes:
360 names = map(_os.fsencode, names)
Tim Petersa0d55de2002-08-09 18:01:01 +0000361
Guido van Rossum805365e2007-05-07 22:24:25 +0000362 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000363 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000364 file = _os.path.join(dir, prefix + name + suffix)
365 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000366 _os.mkdir(file, 0o700)
Florent Xicluna68f71a32011-10-28 16:06:23 +0200367 except FileExistsError:
368 continue # try again
Serhiy Storchaka5d6b7b12015-05-20 00:11:48 +0300369 except PermissionError:
370 # This exception is thrown when a directory with the chosen name
371 # already exists on windows.
372 if (_os.name == 'nt' and _os.path.isdir(dir) and
373 _os.access(dir, _os.W_OK)):
374 continue
375 else:
376 raise
Gregory P. Smithad577b92015-05-22 16:18:14 -0700377 return file
Guido van Rossum0e548712002-08-09 16:14:33 +0000378
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200379 raise FileExistsError(_errno.EEXIST,
380 "No usable temporary directory name found")
Guido van Rossum0e548712002-08-09 16:14:33 +0000381
Guido van Rossume888cdc2002-08-17 14:50:24 +0000382def mktemp(suffix="", prefix=template, dir=None):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000383 """User-callable function to return a unique temporary file name. The
Guido van Rossum0e548712002-08-09 16:14:33 +0000384 file is not created.
385
Martin Panter9b566c32015-11-07 00:32:50 +0000386 Arguments are similar to mkstemp, except that the 'text' argument is
387 not accepted, and suffix=None, prefix=None and bytes file names are not
388 supported.
Guido van Rossum0e548712002-08-09 16:14:33 +0000389
Gregory P. Smithad577b92015-05-22 16:18:14 -0700390 THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may
391 refer to a file that did not exist at some point, but by the time
Guido van Rossum0e548712002-08-09 16:14:33 +0000392 you get around to creating it, someone else may have beaten you to
393 the punch.
394 """
395
Guido van Rossum44f602d2002-11-22 15:56:29 +0000396## from warnings import warn as _warn
397## _warn("mktemp is a potential security risk to your program",
398## RuntimeWarning, stacklevel=2)
Guido van Rossum0e548712002-08-09 16:14:33 +0000399
Guido van Rossume888cdc2002-08-17 14:50:24 +0000400 if dir is None:
401 dir = gettempdir()
402
Guido van Rossum0e548712002-08-09 16:14:33 +0000403 names = _get_candidate_names()
Guido van Rossum805365e2007-05-07 22:24:25 +0000404 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000405 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000406 file = _os.path.join(dir, prefix + name + suffix)
Guido van Rossumb256159392003-11-10 02:16:36 +0000407 if not _exists(file):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000408 return file
Guido van Rossumca549821997-08-12 18:00:12 +0000409
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200410 raise FileExistsError(_errno.EEXIST,
411 "No usable temporary filename found")
Guido van Rossumca549821997-08-12 18:00:12 +0000412
Christian Heimes3ecfea712008-02-09 20:51:34 +0000413
Antoine Pitrou17c93262013-12-21 22:14:56 +0100414class _TemporaryFileCloser:
415 """A separate object allowing proper closing of a temporary file's
416 underlying file object, without adding a __del__ method to the
417 temporary file."""
Tim Petersa255a722001-12-18 22:32:40 +0000418
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200419 file = None # Set here since __del__ checks it
Serhiy Storchaka99e033b2014-01-27 11:18:27 +0200420 close_called = False
421
Guido van Rossumd8faa362007-04-27 19:54:29 +0000422 def __init__(self, file, name, delete=True):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000423 self.file = file
Guido van Rossum0e548712002-08-09 16:14:33 +0000424 self.name = name
Guido van Rossumd8faa362007-04-27 19:54:29 +0000425 self.delete = delete
Guido van Rossumca549821997-08-12 18:00:12 +0000426
Guido van Rossum0e548712002-08-09 16:14:33 +0000427 # NT provides delete-on-close as a primitive, so we don't need
428 # the wrapper to do anything special. We still use it so that
429 # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
430 if _os.name != 'nt':
Guido van Rossum0e548712002-08-09 16:14:33 +0000431 # Cache the unlinker so we don't get spurious errors at
432 # shutdown when the module-level "os" is None'd out. Note
433 # that this must be referenced as self.unlink, because the
434 # name TemporaryFileWrapper may also get None'd out before
435 # __del__ is called.
Tim Peters1baa22a2001-01-12 10:02:46 +0000436
Serhiy Storchaka99e033b2014-01-27 11:18:27 +0200437 def close(self, unlink=_os.unlink):
438 if not self.close_called and self.file is not None:
Tim Peters6ef966e2002-11-21 15:48:33 +0000439 self.close_called = True
Serhiy Storchaka7e7a3db2015-04-10 13:24:41 +0300440 try:
441 self.file.close()
442 finally:
443 if self.delete:
444 unlink(self.name)
Tim Peters1baa22a2001-01-12 10:02:46 +0000445
Antoine Pitrou17c93262013-12-21 22:14:56 +0100446 # Need to ensure the file is deleted on __del__
Guido van Rossum0e548712002-08-09 16:14:33 +0000447 def __del__(self):
448 self.close()
Tim Peters1baa22a2001-01-12 10:02:46 +0000449
Benjamin Peterson98d23f22009-06-30 22:27:25 +0000450 else:
Antoine Pitrou17c93262013-12-21 22:14:56 +0100451 def close(self):
452 if not self.close_called:
453 self.close_called = True
454 self.file.close()
455
456
457class _TemporaryFileWrapper:
458 """Temporary file wrapper
459
460 This class provides a wrapper around files opened for
461 temporary use. In particular, it seeks to automatically
462 remove the file when it is no longer needed.
463 """
464
465 def __init__(self, file, name, delete=True):
466 self.file = file
467 self.name = name
468 self.delete = delete
469 self._closer = _TemporaryFileCloser(file, name, delete)
470
471 def __getattr__(self, name):
472 # Attribute lookups are delegated to the underlying file
473 # and cached for non-numeric results
474 # (i.e. methods are cached, closed and friends are not)
475 file = self.__dict__['file']
476 a = getattr(file, name)
477 if hasattr(a, '__call__'):
478 func = a
479 @_functools.wraps(func)
480 def func_wrapper(*args, **kwargs):
481 return func(*args, **kwargs)
482 # Avoid closing the file as long as the wrapper is alive,
483 # see issue #18879.
484 func_wrapper._closer = self._closer
485 a = func_wrapper
486 if not isinstance(a, int):
487 setattr(self, name, a)
488 return a
489
490 # The underlying __enter__ method returns the wrong object
491 # (self.file) so override it to return the wrapper
492 def __enter__(self):
493 self.file.__enter__()
494 return self
495
496 # Need to trap __exit__ as well to ensure the file gets
497 # deleted when used in a with statement
498 def __exit__(self, exc, value, tb):
499 result = self.file.__exit__(exc, value, tb)
500 self.close()
501 return result
502
503 def close(self):
504 """
505 Close the temporary file, possibly deleting it.
506 """
507 self._closer.close()
508
509 # iter() doesn't use __getattr__ to find the __iter__ method
510 def __iter__(self):
Serhiy Storchakad83b7c22015-03-20 16:11:20 +0200511 # Don't return iter(self.file), but yield from it to avoid closing
R David Murray75ed90a2015-03-22 12:33:46 -0400512 # file as long as it's being used as iterator (see issue #23700). We
513 # can't use 'yield from' here because iter(file) returns the file
514 # object itself, which has a close method, and thus the file would get
515 # closed when the generator is finalized, due to PEP380 semantics.
Serhiy Storchakad83b7c22015-03-20 16:11:20 +0200516 for line in self.file:
517 yield line
Christian Heimes3ecfea712008-02-09 20:51:34 +0000518
519
Guido van Rossumf0c74162007-08-28 03:29:45 +0000520def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None,
Gregory P. Smithad577b92015-05-22 16:18:14 -0700521 newline=None, suffix=None, prefix=None,
sth825aab92018-05-23 07:07:01 +0200522 dir=None, delete=True, *, errors=None):
Guido van Rossum0e548712002-08-09 16:14:33 +0000523 """Create and return a temporary file.
524 Arguments:
525 'prefix', 'suffix', 'dir' -- as for mkstemp.
Guido van Rossumf0c74162007-08-28 03:29:45 +0000526 'mode' -- the mode argument to io.open (default "w+b").
527 'buffering' -- the buffer size argument to io.open (default -1).
528 'encoding' -- the encoding argument to io.open (default None)
529 'newline' -- the newline argument to io.open (default None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000530 'delete' -- whether the file is deleted on close (default True).
sth825aab92018-05-23 07:07:01 +0200531 'errors' -- the errors argument to io.open (default None)
Guido van Rossum0e548712002-08-09 16:14:33 +0000532 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000533
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000534 Returns an object with a file-like interface; the name of the file
Martin Panter1f0e1f32016-02-22 10:10:00 +0000535 is accessible as its 'name' attribute. The file will be automatically
536 deleted when it is closed unless the 'delete' argument is set to False.
Guido van Rossum0e548712002-08-09 16:14:33 +0000537 """
Tim Peters1baa22a2001-01-12 10:02:46 +0000538
Gregory P. Smithad577b92015-05-22 16:18:14 -0700539 prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
Guido van Rossume888cdc2002-08-17 14:50:24 +0000540
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000541 flags = _bin_openflags
Tim Peters1baa22a2001-01-12 10:02:46 +0000542
Guido van Rossum0e548712002-08-09 16:14:33 +0000543 # Setting O_TEMPORARY in the flags causes the OS to delete
544 # the file when it is closed. This is only supported by Windows.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000545 if _os.name == 'nt' and delete:
Guido van Rossum0e548712002-08-09 16:14:33 +0000546 flags |= _os.O_TEMPORARY
Tim Peters1baa22a2001-01-12 10:02:46 +0000547
Gregory P. Smithad577b92015-05-22 16:18:14 -0700548 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type)
Victor Stinner1f99f9d2014-03-25 09:18:04 +0100549 try:
550 file = _io.open(fd, mode, buffering=buffering,
sth825aab92018-05-23 07:07:01 +0200551 newline=newline, encoding=encoding, errors=errors)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000552
Victor Stinner1f99f9d2014-03-25 09:18:04 +0100553 return _TemporaryFileWrapper(file, name, delete)
Martin Panter7869a222016-02-28 05:22:20 +0000554 except BaseException:
555 _os.unlink(name)
Victor Stinner1f99f9d2014-03-25 09:18:04 +0100556 _os.close(fd)
557 raise
Guido van Rossum0e548712002-08-09 16:14:33 +0000558
Jason Tishler80c02af2002-08-14 15:10:09 +0000559if _os.name != 'posix' or _os.sys.platform == 'cygwin':
560 # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
561 # while it is open.
Guido van Rossum0e548712002-08-09 16:14:33 +0000562 TemporaryFile = NamedTemporaryFile
Tim Peters1baa22a2001-01-12 10:02:46 +0000563
564else:
Victor Stinnerd967fc92014-06-05 14:27:45 +0200565 # Is the O_TMPFILE flag available and does it work?
566 # The flag is set to False if os.open(dir, os.O_TMPFILE) raises an
567 # IsADirectoryError exception
568 _O_TMPFILE_WORKS = hasattr(_os, 'O_TMPFILE')
569
Guido van Rossumf0c74162007-08-28 03:29:45 +0000570 def TemporaryFile(mode='w+b', buffering=-1, encoding=None,
Gregory P. Smithad577b92015-05-22 16:18:14 -0700571 newline=None, suffix=None, prefix=None,
sth825aab92018-05-23 07:07:01 +0200572 dir=None, *, errors=None):
Guido van Rossum0e548712002-08-09 16:14:33 +0000573 """Create and return a temporary file.
574 Arguments:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000575 'prefix', 'suffix', 'dir' -- as for mkstemp.
Guido van Rossumf0c74162007-08-28 03:29:45 +0000576 'mode' -- the mode argument to io.open (default "w+b").
577 'buffering' -- the buffer size argument to io.open (default -1).
578 'encoding' -- the encoding argument to io.open (default None)
579 'newline' -- the newline argument to io.open (default None)
sth825aab92018-05-23 07:07:01 +0200580 'errors' -- the errors argument to io.open (default None)
Guido van Rossum0e548712002-08-09 16:14:33 +0000581 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000582
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000583 Returns an object with a file-like interface. The file has no
584 name, and will cease to exist when it is closed.
Guido van Rossum0e548712002-08-09 16:14:33 +0000585 """
Victor Stinnerd967fc92014-06-05 14:27:45 +0200586 global _O_TMPFILE_WORKS
Guido van Rossum0e548712002-08-09 16:14:33 +0000587
Gregory P. Smithad577b92015-05-22 16:18:14 -0700588 prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
Guido van Rossume888cdc2002-08-17 14:50:24 +0000589
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000590 flags = _bin_openflags
Victor Stinnerd967fc92014-06-05 14:27:45 +0200591 if _O_TMPFILE_WORKS:
592 try:
593 flags2 = (flags | _os.O_TMPFILE) & ~_os.O_CREAT
594 fd = _os.open(dir, flags2, 0o600)
595 except IsADirectoryError:
Victor Stinner9aba8c82015-10-21 00:15:08 +0200596 # Linux kernel older than 3.11 ignores the O_TMPFILE flag:
597 # O_TMPFILE is read as O_DIRECTORY. Trying to open a directory
598 # with O_RDWR|O_DIRECTORY fails with IsADirectoryError, a
599 # directory cannot be open to write. Set flag to False to not
600 # try again.
Victor Stinnerd967fc92014-06-05 14:27:45 +0200601 _O_TMPFILE_WORKS = False
602 except OSError:
603 # The filesystem of the directory does not support O_TMPFILE.
604 # For example, OSError(95, 'Operation not supported').
Victor Stinner9aba8c82015-10-21 00:15:08 +0200605 #
606 # On Linux kernel older than 3.11, trying to open a regular
607 # file (or a symbolic link to a regular file) with O_TMPFILE
608 # fails with NotADirectoryError, because O_TMPFILE is read as
609 # O_DIRECTORY.
Victor Stinnerd967fc92014-06-05 14:27:45 +0200610 pass
611 else:
612 try:
613 return _io.open(fd, mode, buffering=buffering,
sth825aab92018-05-23 07:07:01 +0200614 newline=newline, encoding=encoding,
615 errors=errors)
Victor Stinnerd967fc92014-06-05 14:27:45 +0200616 except:
617 _os.close(fd)
618 raise
619 # Fallback to _mkstemp_inner().
Guido van Rossum0e548712002-08-09 16:14:33 +0000620
Gregory P. Smithad577b92015-05-22 16:18:14 -0700621 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type)
Guido van Rossum0e548712002-08-09 16:14:33 +0000622 try:
623 _os.unlink(name)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000624 return _io.open(fd, mode, buffering=buffering,
sth825aab92018-05-23 07:07:01 +0200625 newline=newline, encoding=encoding, errors=errors)
Guido van Rossum0e548712002-08-09 16:14:33 +0000626 except:
627 _os.close(fd)
628 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +0000629
630class SpooledTemporaryFile:
Serhiy Storchaka4f169a72013-02-09 11:46:42 +0200631 """Temporary file wrapper, specialized to switch from BytesIO
632 or StringIO to a real file when it exceeds a certain size or
Guido van Rossumd8faa362007-04-27 19:54:29 +0000633 when a fileno is needed.
634 """
635 _rolled = False
636
Guido van Rossumf0c74162007-08-28 03:29:45 +0000637 def __init__(self, max_size=0, mode='w+b', buffering=-1,
638 encoding=None, newline=None,
sth825aab92018-05-23 07:07:01 +0200639 suffix=None, prefix=None, dir=None, *, errors=None):
Guido van Rossum9a634702007-07-09 10:24:45 +0000640 if 'b' in mode:
641 self._file = _io.BytesIO()
642 else:
Guido van Rossum5d212552007-10-29 16:42:51 +0000643 # Setting newline="\n" avoids newline translation;
644 # this is important because otherwise on Windows we'd
Yury Selivanov0b866602014-09-26 17:08:21 -0400645 # get double newline translation upon rollover().
Alexandre Vassalotti3ade6f92008-06-12 01:13:54 +0000646 self._file = _io.StringIO(newline="\n")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000647 self._max_size = max_size
648 self._rolled = False
Guido van Rossumf0c74162007-08-28 03:29:45 +0000649 self._TemporaryFileArgs = {'mode': mode, 'buffering': buffering,
650 'suffix': suffix, 'prefix': prefix,
651 'encoding': encoding, 'newline': newline,
sth825aab92018-05-23 07:07:01 +0200652 'dir': dir, 'errors': errors}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000653
654 def _check(self, file):
655 if self._rolled: return
656 max_size = self._max_size
657 if max_size and file.tell() > max_size:
658 self.rollover()
659
660 def rollover(self):
661 if self._rolled: return
662 file = self._file
Guido van Rossumf0c74162007-08-28 03:29:45 +0000663 newfile = self._file = TemporaryFile(**self._TemporaryFileArgs)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000664 del self._TemporaryFileArgs
665
666 newfile.write(file.getvalue())
667 newfile.seek(file.tell(), 0)
668
669 self._rolled = True
670
Christian Heimes3ecfea712008-02-09 20:51:34 +0000671 # The method caching trick from NamedTemporaryFile
672 # won't work here, because _file may change from a
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300673 # BytesIO/StringIO instance to a real file. So we list
Christian Heimes3ecfea712008-02-09 20:51:34 +0000674 # all the methods directly.
675
676 # Context management protocol
677 def __enter__(self):
678 if self._file.closed:
679 raise ValueError("Cannot enter context with closed file")
680 return self
681
682 def __exit__(self, exc, value, tb):
683 self._file.close()
684
Guido van Rossumd8faa362007-04-27 19:54:29 +0000685 # file protocol
686 def __iter__(self):
687 return self._file.__iter__()
688
689 def close(self):
690 self._file.close()
691
692 @property
693 def closed(self):
694 return self._file.closed
695
696 @property
697 def encoding(self):
sth825aab92018-05-23 07:07:01 +0200698 return self._file.encoding
699
700 @property
701 def errors(self):
702 return self._file.errors
Guido van Rossumd8faa362007-04-27 19:54:29 +0000703
704 def fileno(self):
705 self.rollover()
706 return self._file.fileno()
707
708 def flush(self):
709 self._file.flush()
710
711 def isatty(self):
712 return self._file.isatty()
713
714 @property
715 def mode(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200716 try:
717 return self._file.mode
718 except AttributeError:
719 return self._TemporaryFileArgs['mode']
Guido van Rossumd8faa362007-04-27 19:54:29 +0000720
721 @property
722 def name(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200723 try:
724 return self._file.name
725 except AttributeError:
726 return None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000727
728 @property
729 def newlines(self):
sth825aab92018-05-23 07:07:01 +0200730 return self._file.newlines
Guido van Rossumd8faa362007-04-27 19:54:29 +0000731
732 def read(self, *args):
733 return self._file.read(*args)
734
735 def readline(self, *args):
736 return self._file.readline(*args)
737
738 def readlines(self, *args):
739 return self._file.readlines(*args)
740
741 def seek(self, *args):
742 self._file.seek(*args)
743
744 @property
745 def softspace(self):
746 return self._file.softspace
747
748 def tell(self):
749 return self._file.tell()
750
Antoine Pitrou0e86a582011-11-25 18:03:09 +0100751 def truncate(self, size=None):
752 if size is None:
753 self._file.truncate()
754 else:
755 if size > self._max_size:
756 self.rollover()
757 self._file.truncate(size)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000758
759 def write(self, s):
760 file = self._file
761 rv = file.write(s)
762 self._check(file)
763 return rv
764
765 def writelines(self, iterable):
766 file = self._file
767 rv = file.writelines(iterable)
768 self._check(file)
769 return rv
770
Nick Coghlan543af752010-10-24 11:23:25 +0000771
772class TemporaryDirectory(object):
773 """Create and return a temporary directory. This has the same
774 behavior as mkdtemp but can be used as a context manager. For
775 example:
776
777 with TemporaryDirectory() as tmpdir:
778 ...
779
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300780 Upon exiting the context, the directory and everything contained
Nick Coghlan543af752010-10-24 11:23:25 +0000781 in it are removed.
782 """
783
Gregory P. Smithad577b92015-05-22 16:18:14 -0700784 def __init__(self, suffix=None, prefix=None, dir=None):
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000785 self.name = mkdtemp(suffix, prefix, dir)
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200786 self._finalizer = _weakref.finalize(
787 self, self._cleanup, self.name,
788 warn_message="Implicitly cleaning up {!r}".format(self))
789
790 @classmethod
Serhiy Storchaka5e193ac2014-09-24 13:26:25 +0300791 def _cleanup(cls, name, warn_message):
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200792 _shutil.rmtree(name)
Serhiy Storchaka5e193ac2014-09-24 13:26:25 +0300793 _warnings.warn(warn_message, ResourceWarning)
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200794
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000795 def __repr__(self):
796 return "<{} {!r}>".format(self.__class__.__name__, self.name)
Nick Coghlan543af752010-10-24 11:23:25 +0000797
798 def __enter__(self):
799 return self.name
800
Nick Coghlan543af752010-10-24 11:23:25 +0000801 def __exit__(self, exc, value, tb):
802 self.cleanup()
803
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200804 def cleanup(self):
Serhiy Storchaka5e193ac2014-09-24 13:26:25 +0300805 if self._finalizer.detach():
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200806 _shutil.rmtree(self.name)