blob: 2f1f9fda7895bd3d83dcfe990468888e73707c1a [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
Guido van Rossum0e548712002-08-09 16:14:33 +000047
Guido van Rossumd8faa362007-04-27 19:54:29 +000048try:
Georg Brandl2067bfd2008-05-25 13:05:15 +000049 import _thread
Brett Cannoncd171c82013-07-04 17:43:24 -040050except ImportError:
Georg Brandl2067bfd2008-05-25 13:05:15 +000051 import _dummy_thread as _thread
Guido van Rossuma0934242002-12-30 22:36:09 +000052_allocate_lock = _thread.allocate_lock
Guido van Rossum0e548712002-08-09 16:14:33 +000053
54_text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL
Tim Petersa0d55de2002-08-09 18:01:01 +000055if hasattr(_os, 'O_NOFOLLOW'):
56 _text_openflags |= _os.O_NOFOLLOW
Guido van Rossum0e548712002-08-09 16:14:33 +000057
58_bin_openflags = _text_openflags
Tim Petersa0d55de2002-08-09 18:01:01 +000059if hasattr(_os, 'O_BINARY'):
60 _bin_openflags |= _os.O_BINARY
Guido van Rossum0e548712002-08-09 16:14:33 +000061
62if hasattr(_os, 'TMP_MAX'):
63 TMP_MAX = _os.TMP_MAX
64else:
65 TMP_MAX = 10000
66
Gregory P. Smithad577b92015-05-22 16:18:14 -070067# This variable _was_ unused for legacy reasons, see issue 10354.
68# But as of 3.5 we actually use it at runtime so changing it would
69# have a possibly desirable side effect... But we do not want to support
70# that as an API. It is undocumented on purpose. Do not depend on this.
Tim Petersbd7b4c72002-08-13 23:33:56 +000071template = "tmp"
Guido van Rossum0e548712002-08-09 16:14:33 +000072
Guido van Rossum0e548712002-08-09 16:14:33 +000073# Internal routines.
74
75_once_lock = _allocate_lock()
76
Guido van Rossumb256159392003-11-10 02:16:36 +000077if hasattr(_os, "lstat"):
78 _stat = _os.lstat
79elif hasattr(_os, "stat"):
80 _stat = _os.stat
81else:
Florent Xicluna68f71a32011-10-28 16:06:23 +020082 # Fallback. All we need is something that raises OSError if the
Guido van Rossumb256159392003-11-10 02:16:36 +000083 # file doesn't exist.
84 def _stat(fn):
Victor Stinnerdaf45552013-08-28 00:53:59 +020085 fd = _os.open(fn, _os.O_RDONLY)
Victor Stinner69b1e262014-03-20 08:50:52 +010086 _os.close(fd)
Guido van Rossumb256159392003-11-10 02:16:36 +000087
88def _exists(fn):
89 try:
90 _stat(fn)
Florent Xicluna68f71a32011-10-28 16:06:23 +020091 except OSError:
Guido van Rossumb256159392003-11-10 02:16:36 +000092 return False
93 else:
94 return True
95
Gregory P. Smithad577b92015-05-22 16:18:14 -070096
97def _infer_return_type(*args):
98 """Look at the type of all args and divine their implied return type."""
99 return_type = None
100 for arg in args:
101 if arg is None:
102 continue
103 if isinstance(arg, bytes):
104 if return_type is str:
105 raise TypeError("Can't mix bytes and non-bytes in "
106 "path components.")
107 return_type = bytes
108 else:
109 if return_type is bytes:
110 raise TypeError("Can't mix bytes and non-bytes in "
111 "path components.")
112 return_type = str
113 if return_type is None:
114 return str # tempfile APIs return a str by default.
115 return return_type
116
117
118def _sanitize_params(prefix, suffix, dir):
119 """Common parameter processing for most APIs in this module."""
120 output_type = _infer_return_type(prefix, suffix, dir)
121 if suffix is None:
122 suffix = output_type()
123 if prefix is None:
124 if output_type is str:
125 prefix = template
126 else:
127 prefix = _os.fsencode(template)
128 if dir is None:
129 if output_type is str:
130 dir = gettempdir()
131 else:
132 dir = gettempdirb()
133 return prefix, suffix, dir, output_type
134
135
Guido van Rossum0e548712002-08-09 16:14:33 +0000136class _RandomNameSequence:
137 """An instance of _RandomNameSequence generates an endless
138 sequence of unpredictable strings which can safely be incorporated
139 into file names. Each string is six characters long. Multiple
140 threads can safely use the same instance at the same time.
141
142 _RandomNameSequence is an iterator."""
143
Raymond Hettinger572895b2010-11-09 03:43:58 +0000144 characters = "abcdefghijklmnopqrstuvwxyz0123456789_"
Guido van Rossum0e548712002-08-09 16:14:33 +0000145
Antoine Pitrou4558bad2011-11-25 21:28:15 +0100146 @property
147 def rng(self):
148 cur_pid = _os.getpid()
149 if cur_pid != getattr(self, '_rng_pid', None):
150 self._rng = _Random()
151 self._rng_pid = cur_pid
152 return self._rng
Tim Peters97701b52002-11-21 15:59:59 +0000153
Guido van Rossum0e548712002-08-09 16:14:33 +0000154 def __iter__(self):
155 return self
156
Georg Brandla18af4e2007-04-21 15:47:16 +0000157 def __next__(self):
Guido van Rossum0e548712002-08-09 16:14:33 +0000158 c = self.characters
Tim Peters97701b52002-11-21 15:59:59 +0000159 choose = self.rng.choice
Victor Stinner97869102013-08-14 01:28:28 +0200160 letters = [choose(c) for dummy in range(8)]
Raymond Hettinger572895b2010-11-09 03:43:58 +0000161 return ''.join(letters)
Guido van Rossum0e548712002-08-09 16:14:33 +0000162
163def _candidate_tempdir_list():
164 """Generate a list of candidate temporary directories which
165 _get_default_tempdir will try."""
166
167 dirlist = []
168
169 # First, try the environment.
170 for envname in 'TMPDIR', 'TEMP', 'TMP':
171 dirname = _os.getenv(envname)
172 if dirname: dirlist.append(dirname)
173
174 # Failing that, try OS-specific locations.
Alexandre Vassalottieca20b62008-05-16 02:54:33 +0000175 if _os.name == 'nt':
Guido van Rossum0e548712002-08-09 16:14:33 +0000176 dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
177 else:
178 dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
179
180 # As a last resort, the current directory.
181 try:
182 dirlist.append(_os.getcwd())
Florent Xicluna68f71a32011-10-28 16:06:23 +0200183 except (AttributeError, OSError):
Guido van Rossum0e548712002-08-09 16:14:33 +0000184 dirlist.append(_os.curdir)
185
186 return dirlist
Tim Petersa0d55de2002-08-09 18:01:01 +0000187
Guido van Rossum0e548712002-08-09 16:14:33 +0000188def _get_default_tempdir():
189 """Calculate the default directory to use for temporary files.
Guido van Rossume888cdc2002-08-17 14:50:24 +0000190 This routine should be called exactly once.
Guido van Rossum0e548712002-08-09 16:14:33 +0000191
192 We determine whether or not a candidate temp dir is usable by
193 trying to create and write to a file in that directory. If this
194 is successful, the test file is deleted. To prevent denial of
195 service, the name of the test file must be randomized."""
196
197 namer = _RandomNameSequence()
198 dirlist = _candidate_tempdir_list()
Guido van Rossum0e548712002-08-09 16:14:33 +0000199
200 for dir in dirlist:
201 if dir != _os.curdir:
Tim Golden6d09f092013-10-25 18:38:16 +0100202 dir = _os.path.abspath(dir)
Guido van Rossum0e548712002-08-09 16:14:33 +0000203 # Try only a few names per directory.
Guido van Rossum805365e2007-05-07 22:24:25 +0000204 for seq in range(100):
Georg Brandla18af4e2007-04-21 15:47:16 +0000205 name = next(namer)
Guido van Rossum0e548712002-08-09 16:14:33 +0000206 filename = _os.path.join(dir, name)
207 try:
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000208 fd = _os.open(filename, _bin_openflags, 0o600)
Serhiy Storchakaf6b361e2013-02-13 00:35:30 +0200209 try:
210 try:
Serhiy Storchaka76a2ed12013-02-13 00:59:26 +0200211 with _io.open(fd, 'wb', closefd=False) as fp:
212 fp.write(b'blat')
Serhiy Storchakaf6b361e2013-02-13 00:35:30 +0200213 finally:
214 _os.close(fd)
215 finally:
216 _os.unlink(filename)
Guido van Rossum0e548712002-08-09 16:14:33 +0000217 return dir
Florent Xicluna68f71a32011-10-28 16:06:23 +0200218 except FileExistsError:
Guido van Rossum0e548712002-08-09 16:14:33 +0000219 pass
Serhiy Storchaka5d6b7b12015-05-20 00:11:48 +0300220 except PermissionError:
221 # This exception is thrown when a directory with the chosen name
222 # already exists on windows.
223 if (_os.name == 'nt' and _os.path.isdir(dir) and
224 _os.access(dir, _os.W_OK)):
225 continue
226 break # no point trying more names in this directory
Florent Xicluna68f71a32011-10-28 16:06:23 +0200227 except OSError:
228 break # no point trying more names in this directory
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200229 raise FileNotFoundError(_errno.ENOENT,
230 "No usable temporary directory found in %s" %
231 dirlist)
Guido van Rossum0e548712002-08-09 16:14:33 +0000232
Guido van Rossume888cdc2002-08-17 14:50:24 +0000233_name_sequence = None
234
Guido van Rossum0e548712002-08-09 16:14:33 +0000235def _get_candidate_names():
236 """Common setup sequence for all user-callable interfaces."""
237
Guido van Rossume888cdc2002-08-17 14:50:24 +0000238 global _name_sequence
239 if _name_sequence is None:
240 _once_lock.acquire()
241 try:
242 if _name_sequence is None:
243 _name_sequence = _RandomNameSequence()
244 finally:
245 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000246 return _name_sequence
Guido van Rossum41f95031992-03-31 19:02:01 +0000247
248
Gregory P. Smithad577b92015-05-22 16:18:14 -0700249def _mkstemp_inner(dir, pre, suf, flags, output_type):
Guido van Rossum0e548712002-08-09 16:14:33 +0000250 """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
Tim Peters9fadfb02001-01-13 03:04:02 +0000251
Guido van Rossum0e548712002-08-09 16:14:33 +0000252 names = _get_candidate_names()
Gregory P. Smithad577b92015-05-22 16:18:14 -0700253 if output_type is bytes:
254 names = map(_os.fsencode, names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000255
Guido van Rossum805365e2007-05-07 22:24:25 +0000256 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000257 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000258 file = _os.path.join(dir, pre + name + suf)
259 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000260 fd = _os.open(file, flags, 0o600)
Florent Xicluna68f71a32011-10-28 16:06:23 +0200261 except FileExistsError:
262 continue # try again
Eli Benderskyf315df32013-09-06 06:11:19 -0700263 except PermissionError:
264 # This exception is thrown when a directory with the chosen name
265 # already exists on windows.
Serhiy Storchaka5d6b7b12015-05-20 00:11:48 +0300266 if (_os.name == 'nt' and _os.path.isdir(dir) and
267 _os.access(dir, _os.W_OK)):
Eli Benderskyf315df32013-09-06 06:11:19 -0700268 continue
269 else:
270 raise
Gregory P. Smithad577b92015-05-22 16:18:14 -0700271 return (fd, _os.path.abspath(file))
Guido van Rossum0e548712002-08-09 16:14:33 +0000272
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200273 raise FileExistsError(_errno.EEXIST,
274 "No usable temporary file name found")
Tim Petersa0d55de2002-08-09 18:01:01 +0000275
Guido van Rossum0e548712002-08-09 16:14:33 +0000276
277# User visible interfaces.
Guido van Rossumb0e57181998-10-14 20:27:05 +0000278
Guido van Rossum41f95031992-03-31 19:02:01 +0000279def gettempprefix():
Gregory P. Smithad577b92015-05-22 16:18:14 -0700280 """The default prefix for temporary directories."""
Guido van Rossum0e548712002-08-09 16:14:33 +0000281 return template
Tim Peters9fadfb02001-01-13 03:04:02 +0000282
Gregory P. Smithad577b92015-05-22 16:18:14 -0700283def gettempprefixb():
284 """The default prefix for temporary directories as bytes."""
285 return _os.fsencode(gettempprefix())
286
Guido van Rossume888cdc2002-08-17 14:50:24 +0000287tempdir = None
288
Guido van Rossum0e548712002-08-09 16:14:33 +0000289def gettempdir():
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000290 """Accessor for tempfile.tempdir."""
Guido van Rossume888cdc2002-08-17 14:50:24 +0000291 global tempdir
292 if tempdir is None:
293 _once_lock.acquire()
294 try:
295 if tempdir is None:
296 tempdir = _get_default_tempdir()
297 finally:
298 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000299 return tempdir
300
Gregory P. Smithad577b92015-05-22 16:18:14 -0700301def gettempdirb():
302 """A bytes version of tempfile.gettempdir()."""
303 return _os.fsencode(gettempdir())
304
305def mkstemp(suffix=None, prefix=None, dir=None, text=False):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000306 """User-callable function to create and return a unique temporary
Guido van Rossum0e548712002-08-09 16:14:33 +0000307 file. The return value is a pair (fd, name) where fd is the
308 file descriptor returned by os.open, and name is the filename.
309
310 If 'suffix' is specified, the file name will end with that suffix,
311 otherwise there will be no suffix.
312
313 If 'prefix' is specified, the file name will begin with that prefix,
314 otherwise a default prefix is used.
315
316 If 'dir' is specified, the file will be created in that directory,
317 otherwise a default directory is used.
318
Tim Peters04490bf2002-08-14 15:41:26 +0000319 If 'text' is specified and true, the file is opened in text
320 mode. Else (the default) the file is opened in binary mode. On
321 some operating systems, this makes no difference.
Guido van Rossum0e548712002-08-09 16:14:33 +0000322
Gregory P. Smithad577b92015-05-22 16:18:14 -0700323 suffix, prefix and dir must all contain the same type if specified.
324 If they are bytes, the returned name will be bytes; str otherwise.
325 A value of None will cause an appropriate default to be used.
326
Guido van Rossum0e548712002-08-09 16:14:33 +0000327 The file is readable and writable only by the creating user ID.
328 If the operating system uses permission bits to indicate whether a
329 file is executable, the file is executable by no one. The file
330 descriptor is not inherited by children of this process.
331
332 Caller is responsible for deleting the file when done with it.
Tim Peters9fadfb02001-01-13 03:04:02 +0000333 """
334
Gregory P. Smithad577b92015-05-22 16:18:14 -0700335 prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
Guido van Rossume888cdc2002-08-17 14:50:24 +0000336
Tim Peters04490bf2002-08-14 15:41:26 +0000337 if text:
Guido van Rossum0e548712002-08-09 16:14:33 +0000338 flags = _text_openflags
Tim Peters04490bf2002-08-14 15:41:26 +0000339 else:
340 flags = _bin_openflags
Guido van Rossum0e548712002-08-09 16:14:33 +0000341
Gregory P. Smithad577b92015-05-22 16:18:14 -0700342 return _mkstemp_inner(dir, prefix, suffix, flags, output_type)
Guido van Rossumcff34541992-01-14 18:31:56 +0000343
Guido van Rossumeee94981991-11-12 15:38:08 +0000344
Gregory P. Smithad577b92015-05-22 16:18:14 -0700345def mkdtemp(suffix=None, prefix=None, dir=None):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000346 """User-callable function to create and return a unique temporary
Guido van Rossum0e548712002-08-09 16:14:33 +0000347 directory. The return value is the pathname of the directory.
348
Tim Peters04490bf2002-08-14 15:41:26 +0000349 Arguments are as for mkstemp, except that the 'text' argument is
Guido van Rossum0e548712002-08-09 16:14:33 +0000350 not accepted.
351
352 The directory is readable, writable, and searchable only by the
353 creating user.
354
355 Caller is responsible for deleting the directory when done with it.
356 """
357
Gregory P. Smithad577b92015-05-22 16:18:14 -0700358 prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
Guido van Rossume888cdc2002-08-17 14:50:24 +0000359
Guido van Rossum0e548712002-08-09 16:14:33 +0000360 names = _get_candidate_names()
Gregory P. Smithad577b92015-05-22 16:18:14 -0700361 if output_type is bytes:
362 names = map(_os.fsencode, names)
Tim Petersa0d55de2002-08-09 18:01:01 +0000363
Guido van Rossum805365e2007-05-07 22:24:25 +0000364 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000365 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000366 file = _os.path.join(dir, prefix + name + suffix)
367 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000368 _os.mkdir(file, 0o700)
Florent Xicluna68f71a32011-10-28 16:06:23 +0200369 except FileExistsError:
370 continue # try again
Serhiy Storchaka5d6b7b12015-05-20 00:11:48 +0300371 except PermissionError:
372 # This exception is thrown when a directory with the chosen name
373 # already exists on windows.
374 if (_os.name == 'nt' and _os.path.isdir(dir) and
375 _os.access(dir, _os.W_OK)):
376 continue
377 else:
378 raise
Gregory P. Smithad577b92015-05-22 16:18:14 -0700379 return file
Guido van Rossum0e548712002-08-09 16:14:33 +0000380
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200381 raise FileExistsError(_errno.EEXIST,
382 "No usable temporary directory name found")
Guido van Rossum0e548712002-08-09 16:14:33 +0000383
Guido van Rossume888cdc2002-08-17 14:50:24 +0000384def mktemp(suffix="", prefix=template, dir=None):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000385 """User-callable function to return a unique temporary file name. The
Guido van Rossum0e548712002-08-09 16:14:33 +0000386 file is not created.
387
Tim Peters04490bf2002-08-14 15:41:26 +0000388 Arguments are as for mkstemp, except that the 'text' argument is
Guido van Rossum0e548712002-08-09 16:14:33 +0000389 not accepted.
390
Gregory P. Smithad577b92015-05-22 16:18:14 -0700391 THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may
392 refer to a file that did not exist at some point, but by the time
Guido van Rossum0e548712002-08-09 16:14:33 +0000393 you get around to creating it, someone else may have beaten you to
394 the punch.
395 """
396
Guido van Rossum44f602d2002-11-22 15:56:29 +0000397## from warnings import warn as _warn
398## _warn("mktemp is a potential security risk to your program",
399## RuntimeWarning, stacklevel=2)
Guido van Rossum0e548712002-08-09 16:14:33 +0000400
Guido van Rossume888cdc2002-08-17 14:50:24 +0000401 if dir is None:
402 dir = gettempdir()
403
Guido van Rossum0e548712002-08-09 16:14:33 +0000404 names = _get_candidate_names()
Guido van Rossum805365e2007-05-07 22:24:25 +0000405 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000406 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000407 file = _os.path.join(dir, prefix + name + suffix)
Guido van Rossumb256159392003-11-10 02:16:36 +0000408 if not _exists(file):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000409 return file
Guido van Rossumca549821997-08-12 18:00:12 +0000410
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200411 raise FileExistsError(_errno.EEXIST,
412 "No usable temporary filename found")
Guido van Rossumca549821997-08-12 18:00:12 +0000413
Christian Heimes3ecfea712008-02-09 20:51:34 +0000414
Antoine Pitrou17c93262013-12-21 22:14:56 +0100415class _TemporaryFileCloser:
416 """A separate object allowing proper closing of a temporary file's
417 underlying file object, without adding a __del__ method to the
418 temporary file."""
Tim Petersa255a722001-12-18 22:32:40 +0000419
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200420 file = None # Set here since __del__ checks it
Serhiy Storchaka99e033b2014-01-27 11:18:27 +0200421 close_called = False
422
Guido van Rossumd8faa362007-04-27 19:54:29 +0000423 def __init__(self, file, name, delete=True):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000424 self.file = file
Guido van Rossum0e548712002-08-09 16:14:33 +0000425 self.name = name
Guido van Rossumd8faa362007-04-27 19:54:29 +0000426 self.delete = delete
Guido van Rossumca549821997-08-12 18:00:12 +0000427
Guido van Rossum0e548712002-08-09 16:14:33 +0000428 # NT provides delete-on-close as a primitive, so we don't need
429 # the wrapper to do anything special. We still use it so that
430 # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
431 if _os.name != 'nt':
Guido van Rossum0e548712002-08-09 16:14:33 +0000432 # Cache the unlinker so we don't get spurious errors at
433 # shutdown when the module-level "os" is None'd out. Note
434 # that this must be referenced as self.unlink, because the
435 # name TemporaryFileWrapper may also get None'd out before
436 # __del__ is called.
Tim Peters1baa22a2001-01-12 10:02:46 +0000437
Serhiy Storchaka99e033b2014-01-27 11:18:27 +0200438 def close(self, unlink=_os.unlink):
439 if not self.close_called and self.file is not None:
Tim Peters6ef966e2002-11-21 15:48:33 +0000440 self.close_called = True
Serhiy Storchaka7e7a3db2015-04-10 13:24:41 +0300441 try:
442 self.file.close()
443 finally:
444 if self.delete:
445 unlink(self.name)
Tim Peters1baa22a2001-01-12 10:02:46 +0000446
Antoine Pitrou17c93262013-12-21 22:14:56 +0100447 # Need to ensure the file is deleted on __del__
Guido van Rossum0e548712002-08-09 16:14:33 +0000448 def __del__(self):
449 self.close()
Tim Peters1baa22a2001-01-12 10:02:46 +0000450
Benjamin Peterson98d23f22009-06-30 22:27:25 +0000451 else:
Antoine Pitrou17c93262013-12-21 22:14:56 +0100452 def close(self):
453 if not self.close_called:
454 self.close_called = True
455 self.file.close()
456
457
458class _TemporaryFileWrapper:
459 """Temporary file wrapper
460
461 This class provides a wrapper around files opened for
462 temporary use. In particular, it seeks to automatically
463 remove the file when it is no longer needed.
464 """
465
466 def __init__(self, file, name, delete=True):
467 self.file = file
468 self.name = name
469 self.delete = delete
470 self._closer = _TemporaryFileCloser(file, name, delete)
471
472 def __getattr__(self, name):
473 # Attribute lookups are delegated to the underlying file
474 # and cached for non-numeric results
475 # (i.e. methods are cached, closed and friends are not)
476 file = self.__dict__['file']
477 a = getattr(file, name)
478 if hasattr(a, '__call__'):
479 func = a
480 @_functools.wraps(func)
481 def func_wrapper(*args, **kwargs):
482 return func(*args, **kwargs)
483 # Avoid closing the file as long as the wrapper is alive,
484 # see issue #18879.
485 func_wrapper._closer = self._closer
486 a = func_wrapper
487 if not isinstance(a, int):
488 setattr(self, name, a)
489 return a
490
491 # The underlying __enter__ method returns the wrong object
492 # (self.file) so override it to return the wrapper
493 def __enter__(self):
494 self.file.__enter__()
495 return self
496
497 # Need to trap __exit__ as well to ensure the file gets
498 # deleted when used in a with statement
499 def __exit__(self, exc, value, tb):
500 result = self.file.__exit__(exc, value, tb)
501 self.close()
502 return result
503
504 def close(self):
505 """
506 Close the temporary file, possibly deleting it.
507 """
508 self._closer.close()
509
510 # iter() doesn't use __getattr__ to find the __iter__ method
511 def __iter__(self):
Serhiy Storchakad83b7c22015-03-20 16:11:20 +0200512 # Don't return iter(self.file), but yield from it to avoid closing
R David Murray75ed90a2015-03-22 12:33:46 -0400513 # file as long as it's being used as iterator (see issue #23700). We
514 # can't use 'yield from' here because iter(file) returns the file
515 # object itself, which has a close method, and thus the file would get
516 # closed when the generator is finalized, due to PEP380 semantics.
Serhiy Storchakad83b7c22015-03-20 16:11:20 +0200517 for line in self.file:
518 yield line
Christian Heimes3ecfea712008-02-09 20:51:34 +0000519
520
Guido van Rossumf0c74162007-08-28 03:29:45 +0000521def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None,
Gregory P. Smithad577b92015-05-22 16:18:14 -0700522 newline=None, suffix=None, prefix=None,
Guido van Rossumf0c74162007-08-28 03:29:45 +0000523 dir=None, delete=True):
Guido van Rossum0e548712002-08-09 16:14:33 +0000524 """Create and return a temporary file.
525 Arguments:
526 'prefix', 'suffix', 'dir' -- as for mkstemp.
Guido van Rossumf0c74162007-08-28 03:29:45 +0000527 'mode' -- the mode argument to io.open (default "w+b").
528 'buffering' -- the buffer size argument to io.open (default -1).
529 'encoding' -- the encoding argument to io.open (default None)
530 'newline' -- the newline argument to io.open (default None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000531 'delete' -- whether the file is deleted on close (default True).
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
535 is accessible as file.name. The file will be automatically deleted
Guido van Rossumd8faa362007-04-27 19:54:29 +0000536 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,
551 newline=newline, encoding=encoding)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000552
Victor Stinner1f99f9d2014-03-25 09:18:04 +0100553 return _TemporaryFileWrapper(file, name, delete)
554 except Exception:
555 _os.close(fd)
556 raise
Guido van Rossum0e548712002-08-09 16:14:33 +0000557
Jason Tishler80c02af2002-08-14 15:10:09 +0000558if _os.name != 'posix' or _os.sys.platform == 'cygwin':
559 # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
560 # while it is open.
Guido van Rossum0e548712002-08-09 16:14:33 +0000561 TemporaryFile = NamedTemporaryFile
Tim Peters1baa22a2001-01-12 10:02:46 +0000562
563else:
Victor Stinnerd967fc92014-06-05 14:27:45 +0200564 # Is the O_TMPFILE flag available and does it work?
565 # The flag is set to False if os.open(dir, os.O_TMPFILE) raises an
566 # IsADirectoryError exception
567 _O_TMPFILE_WORKS = hasattr(_os, 'O_TMPFILE')
568
Guido van Rossumf0c74162007-08-28 03:29:45 +0000569 def TemporaryFile(mode='w+b', buffering=-1, encoding=None,
Gregory P. Smithad577b92015-05-22 16:18:14 -0700570 newline=None, suffix=None, prefix=None,
Guido van Rossumf0c74162007-08-28 03:29:45 +0000571 dir=None):
Guido van Rossum0e548712002-08-09 16:14:33 +0000572 """Create and return a temporary file.
573 Arguments:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000574 'prefix', 'suffix', 'dir' -- as for mkstemp.
Guido van Rossumf0c74162007-08-28 03:29:45 +0000575 'mode' -- the mode argument to io.open (default "w+b").
576 'buffering' -- the buffer size argument to io.open (default -1).
577 'encoding' -- the encoding argument to io.open (default None)
578 'newline' -- the newline argument to io.open (default None)
Guido van Rossum0e548712002-08-09 16:14:33 +0000579 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000580
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000581 Returns an object with a file-like interface. The file has no
582 name, and will cease to exist when it is closed.
Guido van Rossum0e548712002-08-09 16:14:33 +0000583 """
Victor Stinnerd967fc92014-06-05 14:27:45 +0200584 global _O_TMPFILE_WORKS
Guido van Rossum0e548712002-08-09 16:14:33 +0000585
Gregory P. Smithad577b92015-05-22 16:18:14 -0700586 prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
Guido van Rossume888cdc2002-08-17 14:50:24 +0000587
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000588 flags = _bin_openflags
Victor Stinnerd967fc92014-06-05 14:27:45 +0200589 if _O_TMPFILE_WORKS:
590 try:
591 flags2 = (flags | _os.O_TMPFILE) & ~_os.O_CREAT
592 fd = _os.open(dir, flags2, 0o600)
593 except IsADirectoryError:
594 # Linux kernel older than 3.11 ignores O_TMPFILE flag.
Victor Stinner350985d2014-06-09 00:05:47 +0200595 # Set flag to False to not try again.
Victor Stinnerd967fc92014-06-05 14:27:45 +0200596 _O_TMPFILE_WORKS = False
597 except OSError:
598 # The filesystem of the directory does not support O_TMPFILE.
599 # For example, OSError(95, 'Operation not supported').
600 pass
601 else:
602 try:
603 return _io.open(fd, mode, buffering=buffering,
604 newline=newline, encoding=encoding)
605 except:
606 _os.close(fd)
607 raise
608 # Fallback to _mkstemp_inner().
Guido van Rossum0e548712002-08-09 16:14:33 +0000609
Gregory P. Smithad577b92015-05-22 16:18:14 -0700610 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type)
Guido van Rossum0e548712002-08-09 16:14:33 +0000611 try:
612 _os.unlink(name)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000613 return _io.open(fd, mode, buffering=buffering,
614 newline=newline, encoding=encoding)
Guido van Rossum0e548712002-08-09 16:14:33 +0000615 except:
616 _os.close(fd)
617 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +0000618
619class SpooledTemporaryFile:
Serhiy Storchaka4f169a72013-02-09 11:46:42 +0200620 """Temporary file wrapper, specialized to switch from BytesIO
621 or StringIO to a real file when it exceeds a certain size or
Guido van Rossumd8faa362007-04-27 19:54:29 +0000622 when a fileno is needed.
623 """
624 _rolled = False
625
Guido van Rossumf0c74162007-08-28 03:29:45 +0000626 def __init__(self, max_size=0, mode='w+b', buffering=-1,
627 encoding=None, newline=None,
Gregory P. Smithad577b92015-05-22 16:18:14 -0700628 suffix=None, prefix=None, dir=None):
Guido van Rossum9a634702007-07-09 10:24:45 +0000629 if 'b' in mode:
630 self._file = _io.BytesIO()
631 else:
Guido van Rossum5d212552007-10-29 16:42:51 +0000632 # Setting newline="\n" avoids newline translation;
633 # this is important because otherwise on Windows we'd
Yury Selivanov0b866602014-09-26 17:08:21 -0400634 # get double newline translation upon rollover().
Alexandre Vassalotti3ade6f92008-06-12 01:13:54 +0000635 self._file = _io.StringIO(newline="\n")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000636 self._max_size = max_size
637 self._rolled = False
Guido van Rossumf0c74162007-08-28 03:29:45 +0000638 self._TemporaryFileArgs = {'mode': mode, 'buffering': buffering,
639 'suffix': suffix, 'prefix': prefix,
640 'encoding': encoding, 'newline': newline,
641 'dir': dir}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000642
643 def _check(self, file):
644 if self._rolled: return
645 max_size = self._max_size
646 if max_size and file.tell() > max_size:
647 self.rollover()
648
649 def rollover(self):
650 if self._rolled: return
651 file = self._file
Guido van Rossumf0c74162007-08-28 03:29:45 +0000652 newfile = self._file = TemporaryFile(**self._TemporaryFileArgs)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000653 del self._TemporaryFileArgs
654
655 newfile.write(file.getvalue())
656 newfile.seek(file.tell(), 0)
657
658 self._rolled = True
659
Christian Heimes3ecfea712008-02-09 20:51:34 +0000660 # The method caching trick from NamedTemporaryFile
661 # won't work here, because _file may change from a
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300662 # BytesIO/StringIO instance to a real file. So we list
Christian Heimes3ecfea712008-02-09 20:51:34 +0000663 # all the methods directly.
664
665 # Context management protocol
666 def __enter__(self):
667 if self._file.closed:
668 raise ValueError("Cannot enter context with closed file")
669 return self
670
671 def __exit__(self, exc, value, tb):
672 self._file.close()
673
Guido van Rossumd8faa362007-04-27 19:54:29 +0000674 # file protocol
675 def __iter__(self):
676 return self._file.__iter__()
677
678 def close(self):
679 self._file.close()
680
681 @property
682 def closed(self):
683 return self._file.closed
684
685 @property
686 def encoding(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200687 try:
688 return self._file.encoding
689 except AttributeError:
690 if 'b' in self._TemporaryFileArgs['mode']:
691 raise
692 return self._TemporaryFileArgs['encoding']
Guido van Rossumd8faa362007-04-27 19:54:29 +0000693
694 def fileno(self):
695 self.rollover()
696 return self._file.fileno()
697
698 def flush(self):
699 self._file.flush()
700
701 def isatty(self):
702 return self._file.isatty()
703
704 @property
705 def mode(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200706 try:
707 return self._file.mode
708 except AttributeError:
709 return self._TemporaryFileArgs['mode']
Guido van Rossumd8faa362007-04-27 19:54:29 +0000710
711 @property
712 def name(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200713 try:
714 return self._file.name
715 except AttributeError:
716 return None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000717
718 @property
719 def newlines(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200720 try:
721 return self._file.newlines
722 except AttributeError:
723 if 'b' in self._TemporaryFileArgs['mode']:
724 raise
725 return self._TemporaryFileArgs['newline']
Guido van Rossumd8faa362007-04-27 19:54:29 +0000726
727 def read(self, *args):
728 return self._file.read(*args)
729
730 def readline(self, *args):
731 return self._file.readline(*args)
732
733 def readlines(self, *args):
734 return self._file.readlines(*args)
735
736 def seek(self, *args):
737 self._file.seek(*args)
738
739 @property
740 def softspace(self):
741 return self._file.softspace
742
743 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 Storchaka5e193ac2014-09-24 13:26:25 +0300786 def _cleanup(cls, name, warn_message):
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200787 _shutil.rmtree(name)
Serhiy Storchaka5e193ac2014-09-24 13:26:25 +0300788 _warnings.warn(warn_message, ResourceWarning)
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200789
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000790
791 def __repr__(self):
792 return "<{} {!r}>".format(self.__class__.__name__, self.name)
Nick Coghlan543af752010-10-24 11:23:25 +0000793
794 def __enter__(self):
795 return self.name
796
Nick Coghlan543af752010-10-24 11:23:25 +0000797 def __exit__(self, exc, value, tb):
798 self.cleanup()
799
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200800 def cleanup(self):
Serhiy Storchaka5e193ac2014-09-24 13:26:25 +0300801 if self._finalizer.detach():
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200802 _shutil.rmtree(self.name)