blob: b4b5c88338c35551c606a50d2d89f93284ae4961 [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
4creating temporary files and directories. The interfaces listed
5as "safe" just below can be used without fear of race conditions.
6Those listed as "unsafe" cannot, and are provided for backward
7compatibility only.
Guido van Rossumeee94981991-11-12 15:38:08 +00008
Guido van Rossum0e548712002-08-09 16:14:33 +00009This module also provides some data items to the user:
Guido van Rossumeee94981991-11-12 15:38:08 +000010
Guido van Rossum0e548712002-08-09 16:14:33 +000011 TMP_MAX - maximum number of names that will be tried before
12 giving up.
Guido van Rossum0e548712002-08-09 16:14:33 +000013 tempdir - If this is set to a string before the first use of
14 any routine from this module, it will be considered as
15 another candidate location to store temporary files.
16"""
Skip Montanaro40fc1602001-03-01 04:27:19 +000017
Guido van Rossum0e548712002-08-09 16:14:33 +000018__all__ = [
19 "NamedTemporaryFile", "TemporaryFile", # high level safe interfaces
Nick Coghlan543af752010-10-24 11:23:25 +000020 "SpooledTemporaryFile", "TemporaryDirectory",
Guido van Rossum0e548712002-08-09 16:14:33 +000021 "mkstemp", "mkdtemp", # low level safe interfaces
22 "mktemp", # deprecated unsafe interface
23 "TMP_MAX", "gettempprefix", # constants
24 "tempdir", "gettempdir"
25 ]
Guido van Rossum41f95031992-03-31 19:02:01 +000026
Tim Peters4fd5a062002-01-28 23:11:23 +000027
Guido van Rossum0e548712002-08-09 16:14:33 +000028# Imports.
Tim Peters4fd5a062002-01-28 23:11:23 +000029
Antoine Pitrou17c93262013-12-21 22:14:56 +010030import functools as _functools
Nick Coghlan6b22f3f2010-12-12 15:24:21 +000031import warnings as _warnings
32import sys as _sys
Guido van Rossum9a634702007-07-09 10:24:45 +000033import io as _io
Guido van Rossum0e548712002-08-09 16:14:33 +000034import os as _os
Serhiy Storchaka7451a722013-02-09 22:25:49 +020035import errno as _errno
Guido van Rossum0e548712002-08-09 16:14:33 +000036from random import Random as _Random
37
Guido van Rossumd8faa362007-04-27 19:54:29 +000038try:
Guido van Rossum0e548712002-08-09 16:14:33 +000039 import fcntl as _fcntl
Tim Peters90ee7eb2004-07-18 23:58:17 +000040except ImportError:
Tim Peters291f14e2003-07-22 02:50:01 +000041 def _set_cloexec(fd):
42 pass
43else:
Guido van Rossum0e548712002-08-09 16:14:33 +000044 def _set_cloexec(fd):
Tim Peters90ee7eb2004-07-18 23:58:17 +000045 try:
46 flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0)
Florent Xicluna68f71a32011-10-28 16:06:23 +020047 except OSError:
Tim Peters90ee7eb2004-07-18 23:58:17 +000048 pass
Alex Martellif09994e2003-11-09 16:44:09 +000049 else:
Guido van Rossum0e548712002-08-09 16:14:33 +000050 # flags read successfully, modify
51 flags |= _fcntl.FD_CLOEXEC
52 _fcntl.fcntl(fd, _fcntl.F_SETFD, flags)
Tim Peters291f14e2003-07-22 02:50:01 +000053
Guido van Rossum0e548712002-08-09 16:14:33 +000054
55try:
Georg Brandl2067bfd2008-05-25 13:05:15 +000056 import _thread
Guido van Rossuma0934242002-12-30 22:36:09 +000057except ImportError:
Georg Brandl2067bfd2008-05-25 13:05:15 +000058 import _dummy_thread as _thread
Guido van Rossuma0934242002-12-30 22:36:09 +000059_allocate_lock = _thread.allocate_lock
Guido van Rossum0e548712002-08-09 16:14:33 +000060
61_text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL
Tim Petersa0d55de2002-08-09 18:01:01 +000062if hasattr(_os, 'O_NOINHERIT'):
63 _text_openflags |= _os.O_NOINHERIT
64if hasattr(_os, 'O_NOFOLLOW'):
65 _text_openflags |= _os.O_NOFOLLOW
Guido van Rossum0e548712002-08-09 16:14:33 +000066
67_bin_openflags = _text_openflags
Tim Petersa0d55de2002-08-09 18:01:01 +000068if hasattr(_os, 'O_BINARY'):
69 _bin_openflags |= _os.O_BINARY
Guido van Rossum0e548712002-08-09 16:14:33 +000070
71if hasattr(_os, 'TMP_MAX'):
72 TMP_MAX = _os.TMP_MAX
73else:
74 TMP_MAX = 10000
75
R David Murray3a420c72011-06-22 21:01:13 -040076# Although it does not have an underscore for historical reasons, this
77# variable is an internal implementation detail (see issue 10354).
Tim Petersbd7b4c72002-08-13 23:33:56 +000078template = "tmp"
Guido van Rossum0e548712002-08-09 16:14:33 +000079
Guido van Rossum0e548712002-08-09 16:14:33 +000080# Internal routines.
81
82_once_lock = _allocate_lock()
83
Guido van Rossumb256159392003-11-10 02:16:36 +000084if hasattr(_os, "lstat"):
85 _stat = _os.lstat
86elif hasattr(_os, "stat"):
87 _stat = _os.stat
88else:
Florent Xicluna68f71a32011-10-28 16:06:23 +020089 # Fallback. All we need is something that raises OSError if the
Guido van Rossumb256159392003-11-10 02:16:36 +000090 # file doesn't exist.
91 def _stat(fn):
Florent Xicluna46f5d142011-10-28 21:58:56 +020092 f = open(fn)
Guido van Rossumb256159392003-11-10 02:16:36 +000093 f.close()
94
95def _exists(fn):
96 try:
97 _stat(fn)
Florent Xicluna68f71a32011-10-28 16:06:23 +020098 except OSError:
Guido van Rossumb256159392003-11-10 02:16:36 +000099 return False
100 else:
101 return True
102
Guido van Rossum0e548712002-08-09 16:14:33 +0000103class _RandomNameSequence:
104 """An instance of _RandomNameSequence generates an endless
105 sequence of unpredictable strings which can safely be incorporated
106 into file names. Each string is six characters long. Multiple
107 threads can safely use the same instance at the same time.
108
109 _RandomNameSequence is an iterator."""
110
Raymond Hettinger572895b2010-11-09 03:43:58 +0000111 characters = "abcdefghijklmnopqrstuvwxyz0123456789_"
Guido van Rossum0e548712002-08-09 16:14:33 +0000112
Antoine Pitrou4558bad2011-11-25 21:28:15 +0100113 @property
114 def rng(self):
115 cur_pid = _os.getpid()
116 if cur_pid != getattr(self, '_rng_pid', None):
117 self._rng = _Random()
118 self._rng_pid = cur_pid
119 return self._rng
Tim Peters97701b52002-11-21 15:59:59 +0000120
Guido van Rossum0e548712002-08-09 16:14:33 +0000121 def __iter__(self):
122 return self
123
Georg Brandla18af4e2007-04-21 15:47:16 +0000124 def __next__(self):
Guido van Rossum0e548712002-08-09 16:14:33 +0000125 c = self.characters
Tim Peters97701b52002-11-21 15:59:59 +0000126 choose = self.rng.choice
Raymond Hettinger572895b2010-11-09 03:43:58 +0000127 letters = [choose(c) for dummy in "123456"]
128 return ''.join(letters)
Guido van Rossum0e548712002-08-09 16:14:33 +0000129
130def _candidate_tempdir_list():
131 """Generate a list of candidate temporary directories which
132 _get_default_tempdir will try."""
133
134 dirlist = []
135
136 # First, try the environment.
137 for envname in 'TMPDIR', 'TEMP', 'TMP':
138 dirname = _os.getenv(envname)
139 if dirname: dirlist.append(dirname)
140
141 # Failing that, try OS-specific locations.
Alexandre Vassalottieca20b62008-05-16 02:54:33 +0000142 if _os.name == 'nt':
Guido van Rossum0e548712002-08-09 16:14:33 +0000143 dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
144 else:
145 dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
146
147 # As a last resort, the current directory.
148 try:
149 dirlist.append(_os.getcwd())
Florent Xicluna68f71a32011-10-28 16:06:23 +0200150 except (AttributeError, OSError):
Guido van Rossum0e548712002-08-09 16:14:33 +0000151 dirlist.append(_os.curdir)
152
153 return dirlist
Tim Petersa0d55de2002-08-09 18:01:01 +0000154
Guido van Rossum0e548712002-08-09 16:14:33 +0000155def _get_default_tempdir():
156 """Calculate the default directory to use for temporary files.
Guido van Rossume888cdc2002-08-17 14:50:24 +0000157 This routine should be called exactly once.
Guido van Rossum0e548712002-08-09 16:14:33 +0000158
159 We determine whether or not a candidate temp dir is usable by
160 trying to create and write to a file in that directory. If this
161 is successful, the test file is deleted. To prevent denial of
162 service, the name of the test file must be randomized."""
163
164 namer = _RandomNameSequence()
165 dirlist = _candidate_tempdir_list()
Guido van Rossum0e548712002-08-09 16:14:33 +0000166
167 for dir in dirlist:
168 if dir != _os.curdir:
169 dir = _os.path.normcase(_os.path.abspath(dir))
170 # Try only a few names per directory.
Guido van Rossum805365e2007-05-07 22:24:25 +0000171 for seq in range(100):
Georg Brandla18af4e2007-04-21 15:47:16 +0000172 name = next(namer)
Guido van Rossum0e548712002-08-09 16:14:33 +0000173 filename = _os.path.join(dir, name)
174 try:
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000175 fd = _os.open(filename, _bin_openflags, 0o600)
Serhiy Storchakaf6b361e2013-02-13 00:35:30 +0200176 try:
177 try:
Serhiy Storchaka76a2ed12013-02-13 00:59:26 +0200178 with _io.open(fd, 'wb', closefd=False) as fp:
179 fp.write(b'blat')
Serhiy Storchakaf6b361e2013-02-13 00:35:30 +0200180 finally:
181 _os.close(fd)
182 finally:
183 _os.unlink(filename)
Guido van Rossum0e548712002-08-09 16:14:33 +0000184 return dir
Florent Xicluna68f71a32011-10-28 16:06:23 +0200185 except FileExistsError:
Guido van Rossum0e548712002-08-09 16:14:33 +0000186 pass
Florent Xicluna68f71a32011-10-28 16:06:23 +0200187 except OSError:
188 break # no point trying more names in this directory
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200189 raise FileNotFoundError(_errno.ENOENT,
190 "No usable temporary directory found in %s" %
191 dirlist)
Guido van Rossum0e548712002-08-09 16:14:33 +0000192
Guido van Rossume888cdc2002-08-17 14:50:24 +0000193_name_sequence = None
194
Guido van Rossum0e548712002-08-09 16:14:33 +0000195def _get_candidate_names():
196 """Common setup sequence for all user-callable interfaces."""
197
Guido van Rossume888cdc2002-08-17 14:50:24 +0000198 global _name_sequence
199 if _name_sequence is None:
200 _once_lock.acquire()
201 try:
202 if _name_sequence is None:
203 _name_sequence = _RandomNameSequence()
204 finally:
205 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000206 return _name_sequence
Guido van Rossum41f95031992-03-31 19:02:01 +0000207
208
Guido van Rossum0e548712002-08-09 16:14:33 +0000209def _mkstemp_inner(dir, pre, suf, flags):
210 """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
Tim Peters9fadfb02001-01-13 03:04:02 +0000211
Guido van Rossum0e548712002-08-09 16:14:33 +0000212 names = _get_candidate_names()
213
Guido van Rossum805365e2007-05-07 22:24:25 +0000214 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000215 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000216 file = _os.path.join(dir, pre + name + suf)
217 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000218 fd = _os.open(file, flags, 0o600)
Guido van Rossum0e548712002-08-09 16:14:33 +0000219 _set_cloexec(fd)
Martin v. Löwisd6625482003-10-12 17:37:01 +0000220 return (fd, _os.path.abspath(file))
Florent Xicluna68f71a32011-10-28 16:06:23 +0200221 except FileExistsError:
222 continue # try again
Eli Benderskyf315df32013-09-06 06:11:19 -0700223 except PermissionError:
224 # This exception is thrown when a directory with the chosen name
225 # already exists on windows.
226 if _os.name == 'nt':
227 continue
228 else:
229 raise
Guido van Rossum0e548712002-08-09 16:14:33 +0000230
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200231 raise FileExistsError(_errno.EEXIST,
232 "No usable temporary file name found")
Tim Petersa0d55de2002-08-09 18:01:01 +0000233
Guido van Rossum0e548712002-08-09 16:14:33 +0000234
235# User visible interfaces.
Guido van Rossumb0e57181998-10-14 20:27:05 +0000236
Guido van Rossum41f95031992-03-31 19:02:01 +0000237def gettempprefix():
Guido van Rossum0e548712002-08-09 16:14:33 +0000238 """Accessor for tempdir.template."""
239 return template
Tim Peters9fadfb02001-01-13 03:04:02 +0000240
Guido van Rossume888cdc2002-08-17 14:50:24 +0000241tempdir = None
242
Guido van Rossum0e548712002-08-09 16:14:33 +0000243def gettempdir():
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000244 """Accessor for tempfile.tempdir."""
Guido van Rossume888cdc2002-08-17 14:50:24 +0000245 global tempdir
246 if tempdir is None:
247 _once_lock.acquire()
248 try:
249 if tempdir is None:
250 tempdir = _get_default_tempdir()
251 finally:
252 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000253 return tempdir
254
Guido van Rossume888cdc2002-08-17 14:50:24 +0000255def mkstemp(suffix="", prefix=template, dir=None, text=False):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000256 """User-callable function to create and return a unique temporary
Guido van Rossum0e548712002-08-09 16:14:33 +0000257 file. The return value is a pair (fd, name) where fd is the
258 file descriptor returned by os.open, and name is the filename.
259
260 If 'suffix' is specified, the file name will end with that suffix,
261 otherwise there will be no suffix.
262
263 If 'prefix' is specified, the file name will begin with that prefix,
264 otherwise a default prefix is used.
265
266 If 'dir' is specified, the file will be created in that directory,
267 otherwise a default directory is used.
268
Tim Peters04490bf2002-08-14 15:41:26 +0000269 If 'text' is specified and true, the file is opened in text
270 mode. Else (the default) the file is opened in binary mode. On
271 some operating systems, this makes no difference.
Guido van Rossum0e548712002-08-09 16:14:33 +0000272
273 The file is readable and writable only by the creating user ID.
274 If the operating system uses permission bits to indicate whether a
275 file is executable, the file is executable by no one. The file
276 descriptor is not inherited by children of this process.
277
278 Caller is responsible for deleting the file when done with it.
Tim Peters9fadfb02001-01-13 03:04:02 +0000279 """
280
Guido van Rossume888cdc2002-08-17 14:50:24 +0000281 if dir is None:
282 dir = gettempdir()
283
Tim Peters04490bf2002-08-14 15:41:26 +0000284 if text:
Guido van Rossum0e548712002-08-09 16:14:33 +0000285 flags = _text_openflags
Tim Peters04490bf2002-08-14 15:41:26 +0000286 else:
287 flags = _bin_openflags
Guido van Rossum0e548712002-08-09 16:14:33 +0000288
289 return _mkstemp_inner(dir, prefix, suffix, flags)
Guido van Rossumcff34541992-01-14 18:31:56 +0000290
Guido van Rossumeee94981991-11-12 15:38:08 +0000291
Guido van Rossume888cdc2002-08-17 14:50:24 +0000292def mkdtemp(suffix="", prefix=template, dir=None):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000293 """User-callable function to create and return a unique temporary
Guido van Rossum0e548712002-08-09 16:14:33 +0000294 directory. The return value is the pathname of the directory.
295
Tim Peters04490bf2002-08-14 15:41:26 +0000296 Arguments are as for mkstemp, except that the 'text' argument is
Guido van Rossum0e548712002-08-09 16:14:33 +0000297 not accepted.
298
299 The directory is readable, writable, and searchable only by the
300 creating user.
301
302 Caller is responsible for deleting the directory when done with it.
303 """
304
Guido van Rossume888cdc2002-08-17 14:50:24 +0000305 if dir is None:
306 dir = gettempdir()
307
Guido van Rossum0e548712002-08-09 16:14:33 +0000308 names = _get_candidate_names()
Tim Petersa0d55de2002-08-09 18:01:01 +0000309
Guido van Rossum805365e2007-05-07 22:24:25 +0000310 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000311 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000312 file = _os.path.join(dir, prefix + name + suffix)
313 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000314 _os.mkdir(file, 0o700)
Guido van Rossum0e548712002-08-09 16:14:33 +0000315 return file
Florent Xicluna68f71a32011-10-28 16:06:23 +0200316 except FileExistsError:
317 continue # try again
Guido van Rossum0e548712002-08-09 16:14:33 +0000318
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200319 raise FileExistsError(_errno.EEXIST,
320 "No usable temporary directory name found")
Guido van Rossum0e548712002-08-09 16:14:33 +0000321
Guido van Rossume888cdc2002-08-17 14:50:24 +0000322def mktemp(suffix="", prefix=template, dir=None):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000323 """User-callable function to return a unique temporary file name. The
Guido van Rossum0e548712002-08-09 16:14:33 +0000324 file is not created.
325
Tim Peters04490bf2002-08-14 15:41:26 +0000326 Arguments are as for mkstemp, except that the 'text' argument is
Guido van Rossum0e548712002-08-09 16:14:33 +0000327 not accepted.
328
329 This function is unsafe and should not be used. The file name
330 refers to a file that did not exist at some point, but by the time
331 you get around to creating it, someone else may have beaten you to
332 the punch.
333 """
334
Guido van Rossum44f602d2002-11-22 15:56:29 +0000335## from warnings import warn as _warn
336## _warn("mktemp is a potential security risk to your program",
337## RuntimeWarning, stacklevel=2)
Guido van Rossum0e548712002-08-09 16:14:33 +0000338
Guido van Rossume888cdc2002-08-17 14:50:24 +0000339 if dir is None:
340 dir = gettempdir()
341
Guido van Rossum0e548712002-08-09 16:14:33 +0000342 names = _get_candidate_names()
Guido van Rossum805365e2007-05-07 22:24:25 +0000343 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000344 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000345 file = _os.path.join(dir, prefix + name + suffix)
Guido van Rossumb256159392003-11-10 02:16:36 +0000346 if not _exists(file):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000347 return file
Guido van Rossumca549821997-08-12 18:00:12 +0000348
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200349 raise FileExistsError(_errno.EEXIST,
350 "No usable temporary filename found")
Guido van Rossumca549821997-08-12 18:00:12 +0000351
Christian Heimes3ecfea712008-02-09 20:51:34 +0000352
Antoine Pitrou17c93262013-12-21 22:14:56 +0100353class _TemporaryFileCloser:
354 """A separate object allowing proper closing of a temporary file's
355 underlying file object, without adding a __del__ method to the
356 temporary file."""
Tim Petersa255a722001-12-18 22:32:40 +0000357
Guido van Rossumd8faa362007-04-27 19:54:29 +0000358 def __init__(self, file, name, delete=True):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000359 self.file = file
Guido van Rossum0e548712002-08-09 16:14:33 +0000360 self.name = name
Tim Peters6ef966e2002-11-21 15:48:33 +0000361 self.close_called = False
Guido van Rossumd8faa362007-04-27 19:54:29 +0000362 self.delete = delete
Guido van Rossumca549821997-08-12 18:00:12 +0000363
Guido van Rossum0e548712002-08-09 16:14:33 +0000364 # NT provides delete-on-close as a primitive, so we don't need
365 # the wrapper to do anything special. We still use it so that
366 # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
367 if _os.name != 'nt':
Guido van Rossum0e548712002-08-09 16:14:33 +0000368 # Cache the unlinker so we don't get spurious errors at
369 # shutdown when the module-level "os" is None'd out. Note
370 # that this must be referenced as self.unlink, because the
371 # name TemporaryFileWrapper may also get None'd out before
372 # __del__ is called.
373 unlink = _os.unlink
Tim Peters1baa22a2001-01-12 10:02:46 +0000374
Guido van Rossum0e548712002-08-09 16:14:33 +0000375 def close(self):
376 if not self.close_called:
Tim Peters6ef966e2002-11-21 15:48:33 +0000377 self.close_called = True
Guido van Rossum0e548712002-08-09 16:14:33 +0000378 self.file.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000379 if self.delete:
380 self.unlink(self.name)
Tim Peters1baa22a2001-01-12 10:02:46 +0000381
Antoine Pitrou17c93262013-12-21 22:14:56 +0100382 # Need to ensure the file is deleted on __del__
Guido van Rossum0e548712002-08-09 16:14:33 +0000383 def __del__(self):
384 self.close()
Tim Peters1baa22a2001-01-12 10:02:46 +0000385
Benjamin Peterson98d23f22009-06-30 22:27:25 +0000386 else:
Antoine Pitrou17c93262013-12-21 22:14:56 +0100387 def close(self):
388 if not self.close_called:
389 self.close_called = True
390 self.file.close()
391
392
393class _TemporaryFileWrapper:
394 """Temporary file wrapper
395
396 This class provides a wrapper around files opened for
397 temporary use. In particular, it seeks to automatically
398 remove the file when it is no longer needed.
399 """
400
401 def __init__(self, file, name, delete=True):
402 self.file = file
403 self.name = name
404 self.delete = delete
405 self._closer = _TemporaryFileCloser(file, name, delete)
406
407 def __getattr__(self, name):
408 # Attribute lookups are delegated to the underlying file
409 # and cached for non-numeric results
410 # (i.e. methods are cached, closed and friends are not)
411 file = self.__dict__['file']
412 a = getattr(file, name)
413 if hasattr(a, '__call__'):
414 func = a
415 @_functools.wraps(func)
416 def func_wrapper(*args, **kwargs):
417 return func(*args, **kwargs)
418 # Avoid closing the file as long as the wrapper is alive,
419 # see issue #18879.
420 func_wrapper._closer = self._closer
421 a = func_wrapper
422 if not isinstance(a, int):
423 setattr(self, name, a)
424 return a
425
426 # The underlying __enter__ method returns the wrong object
427 # (self.file) so override it to return the wrapper
428 def __enter__(self):
429 self.file.__enter__()
430 return self
431
432 # Need to trap __exit__ as well to ensure the file gets
433 # deleted when used in a with statement
434 def __exit__(self, exc, value, tb):
435 result = self.file.__exit__(exc, value, tb)
436 self.close()
437 return result
438
439 def close(self):
440 """
441 Close the temporary file, possibly deleting it.
442 """
443 self._closer.close()
444
445 # iter() doesn't use __getattr__ to find the __iter__ method
446 def __iter__(self):
447 return iter(self.file)
Christian Heimes3ecfea712008-02-09 20:51:34 +0000448
449
Guido van Rossumf0c74162007-08-28 03:29:45 +0000450def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None,
451 newline=None, suffix="", prefix=template,
452 dir=None, delete=True):
Guido van Rossum0e548712002-08-09 16:14:33 +0000453 """Create and return a temporary file.
454 Arguments:
455 'prefix', 'suffix', 'dir' -- as for mkstemp.
Guido van Rossumf0c74162007-08-28 03:29:45 +0000456 'mode' -- the mode argument to io.open (default "w+b").
457 'buffering' -- the buffer size argument to io.open (default -1).
458 'encoding' -- the encoding argument to io.open (default None)
459 'newline' -- the newline argument to io.open (default None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000460 'delete' -- whether the file is deleted on close (default True).
Guido van Rossum0e548712002-08-09 16:14:33 +0000461 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000462
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000463 Returns an object with a file-like interface; the name of the file
464 is accessible as file.name. The file will be automatically deleted
Guido van Rossumd8faa362007-04-27 19:54:29 +0000465 when it is closed unless the 'delete' argument is set to False.
Guido van Rossum0e548712002-08-09 16:14:33 +0000466 """
Tim Peters1baa22a2001-01-12 10:02:46 +0000467
Guido van Rossume888cdc2002-08-17 14:50:24 +0000468 if dir is None:
469 dir = gettempdir()
470
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000471 flags = _bin_openflags
Tim Peters1baa22a2001-01-12 10:02:46 +0000472
Guido van Rossum0e548712002-08-09 16:14:33 +0000473 # Setting O_TEMPORARY in the flags causes the OS to delete
474 # the file when it is closed. This is only supported by Windows.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000475 if _os.name == 'nt' and delete:
Guido van Rossum0e548712002-08-09 16:14:33 +0000476 flags |= _os.O_TEMPORARY
Tim Peters1baa22a2001-01-12 10:02:46 +0000477
Guido van Rossum0e548712002-08-09 16:14:33 +0000478 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000479 file = _io.open(fd, mode, buffering=buffering,
480 newline=newline, encoding=encoding)
481
Guido van Rossumd8faa362007-04-27 19:54:29 +0000482 return _TemporaryFileWrapper(file, name, delete)
Guido van Rossum0e548712002-08-09 16:14:33 +0000483
Jason Tishler80c02af2002-08-14 15:10:09 +0000484if _os.name != 'posix' or _os.sys.platform == 'cygwin':
485 # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
486 # while it is open.
Guido van Rossum0e548712002-08-09 16:14:33 +0000487 TemporaryFile = NamedTemporaryFile
Tim Peters1baa22a2001-01-12 10:02:46 +0000488
489else:
Guido van Rossumf0c74162007-08-28 03:29:45 +0000490 def TemporaryFile(mode='w+b', buffering=-1, encoding=None,
491 newline=None, suffix="", prefix=template,
492 dir=None):
Guido van Rossum0e548712002-08-09 16:14:33 +0000493 """Create and return a temporary file.
494 Arguments:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000495 'prefix', 'suffix', 'dir' -- as for mkstemp.
Guido van Rossumf0c74162007-08-28 03:29:45 +0000496 'mode' -- the mode argument to io.open (default "w+b").
497 'buffering' -- the buffer size argument to io.open (default -1).
498 'encoding' -- the encoding argument to io.open (default None)
499 'newline' -- the newline argument to io.open (default None)
Guido van Rossum0e548712002-08-09 16:14:33 +0000500 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000501
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000502 Returns an object with a file-like interface. The file has no
503 name, and will cease to exist when it is closed.
Guido van Rossum0e548712002-08-09 16:14:33 +0000504 """
505
Guido van Rossume888cdc2002-08-17 14:50:24 +0000506 if dir is None:
507 dir = gettempdir()
508
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000509 flags = _bin_openflags
Guido van Rossum0e548712002-08-09 16:14:33 +0000510
511 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
512 try:
513 _os.unlink(name)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000514 return _io.open(fd, mode, buffering=buffering,
515 newline=newline, encoding=encoding)
Guido van Rossum0e548712002-08-09 16:14:33 +0000516 except:
517 _os.close(fd)
518 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +0000519
520class SpooledTemporaryFile:
Serhiy Storchaka4f169a72013-02-09 11:46:42 +0200521 """Temporary file wrapper, specialized to switch from BytesIO
522 or StringIO to a real file when it exceeds a certain size or
Guido van Rossumd8faa362007-04-27 19:54:29 +0000523 when a fileno is needed.
524 """
525 _rolled = False
526
Guido van Rossumf0c74162007-08-28 03:29:45 +0000527 def __init__(self, max_size=0, mode='w+b', buffering=-1,
528 encoding=None, newline=None,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000529 suffix="", prefix=template, dir=None):
Guido van Rossum9a634702007-07-09 10:24:45 +0000530 if 'b' in mode:
531 self._file = _io.BytesIO()
532 else:
Guido van Rossum5d212552007-10-29 16:42:51 +0000533 # Setting newline="\n" avoids newline translation;
534 # this is important because otherwise on Windows we'd
Guido van Rossum98297ee2007-11-06 21:34:58 +0000535 # hget double newline translation upon rollover().
Alexandre Vassalotti3ade6f92008-06-12 01:13:54 +0000536 self._file = _io.StringIO(newline="\n")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000537 self._max_size = max_size
538 self._rolled = False
Guido van Rossumf0c74162007-08-28 03:29:45 +0000539 self._TemporaryFileArgs = {'mode': mode, 'buffering': buffering,
540 'suffix': suffix, 'prefix': prefix,
541 'encoding': encoding, 'newline': newline,
542 'dir': dir}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000543
544 def _check(self, file):
545 if self._rolled: return
546 max_size = self._max_size
547 if max_size and file.tell() > max_size:
548 self.rollover()
549
550 def rollover(self):
551 if self._rolled: return
552 file = self._file
Guido van Rossumf0c74162007-08-28 03:29:45 +0000553 newfile = self._file = TemporaryFile(**self._TemporaryFileArgs)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000554 del self._TemporaryFileArgs
555
556 newfile.write(file.getvalue())
557 newfile.seek(file.tell(), 0)
558
559 self._rolled = True
560
Christian Heimes3ecfea712008-02-09 20:51:34 +0000561 # The method caching trick from NamedTemporaryFile
562 # won't work here, because _file may change from a
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300563 # BytesIO/StringIO instance to a real file. So we list
Christian Heimes3ecfea712008-02-09 20:51:34 +0000564 # all the methods directly.
565
566 # Context management protocol
567 def __enter__(self):
568 if self._file.closed:
569 raise ValueError("Cannot enter context with closed file")
570 return self
571
572 def __exit__(self, exc, value, tb):
573 self._file.close()
574
Guido van Rossumd8faa362007-04-27 19:54:29 +0000575 # file protocol
576 def __iter__(self):
577 return self._file.__iter__()
578
579 def close(self):
580 self._file.close()
581
582 @property
583 def closed(self):
584 return self._file.closed
585
586 @property
587 def encoding(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200588 try:
589 return self._file.encoding
590 except AttributeError:
591 if 'b' in self._TemporaryFileArgs['mode']:
592 raise
593 return self._TemporaryFileArgs['encoding']
Guido van Rossumd8faa362007-04-27 19:54:29 +0000594
595 def fileno(self):
596 self.rollover()
597 return self._file.fileno()
598
599 def flush(self):
600 self._file.flush()
601
602 def isatty(self):
603 return self._file.isatty()
604
605 @property
606 def mode(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200607 try:
608 return self._file.mode
609 except AttributeError:
610 return self._TemporaryFileArgs['mode']
Guido van Rossumd8faa362007-04-27 19:54:29 +0000611
612 @property
613 def name(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200614 try:
615 return self._file.name
616 except AttributeError:
617 return None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000618
619 @property
620 def newlines(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200621 try:
622 return self._file.newlines
623 except AttributeError:
624 if 'b' in self._TemporaryFileArgs['mode']:
625 raise
626 return self._TemporaryFileArgs['newline']
Guido van Rossumd8faa362007-04-27 19:54:29 +0000627
628 def read(self, *args):
629 return self._file.read(*args)
630
631 def readline(self, *args):
632 return self._file.readline(*args)
633
634 def readlines(self, *args):
635 return self._file.readlines(*args)
636
637 def seek(self, *args):
638 self._file.seek(*args)
639
640 @property
641 def softspace(self):
642 return self._file.softspace
643
644 def tell(self):
645 return self._file.tell()
646
Antoine Pitrou0e86a582011-11-25 18:03:09 +0100647 def truncate(self, size=None):
648 if size is None:
649 self._file.truncate()
650 else:
651 if size > self._max_size:
652 self.rollover()
653 self._file.truncate(size)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000654
655 def write(self, s):
656 file = self._file
657 rv = file.write(s)
658 self._check(file)
659 return rv
660
661 def writelines(self, iterable):
662 file = self._file
663 rv = file.writelines(iterable)
664 self._check(file)
665 return rv
666
Nick Coghlan543af752010-10-24 11:23:25 +0000667
668class TemporaryDirectory(object):
669 """Create and return a temporary directory. This has the same
670 behavior as mkdtemp but can be used as a context manager. For
671 example:
672
673 with TemporaryDirectory() as tmpdir:
674 ...
675
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300676 Upon exiting the context, the directory and everything contained
Nick Coghlan543af752010-10-24 11:23:25 +0000677 in it are removed.
678 """
679
680 def __init__(self, suffix="", prefix=template, dir=None):
Nick Coghlan543af752010-10-24 11:23:25 +0000681 self._closed = False
Andrew Svetlov737fb892012-12-18 21:14:22 +0200682 self.name = None # Handle mkdtemp raising an exception
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000683 self.name = mkdtemp(suffix, prefix, dir)
684
685 def __repr__(self):
686 return "<{} {!r}>".format(self.__class__.__name__, self.name)
Nick Coghlan543af752010-10-24 11:23:25 +0000687
688 def __enter__(self):
689 return self.name
690
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000691 def cleanup(self, _warn=False):
692 if self.name and not self._closed:
693 try:
694 self._rmtree(self.name)
695 except (TypeError, AttributeError) as ex:
696 # Issue #10188: Emit a warning on stderr
697 # if the directory could not be cleaned
698 # up due to missing globals
699 if "None" not in str(ex):
700 raise
701 print("ERROR: {!r} while cleaning up {!r}".format(ex, self,),
702 file=_sys.stderr)
703 return
Nick Coghlan543af752010-10-24 11:23:25 +0000704 self._closed = True
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000705 if _warn:
706 self._warn("Implicitly cleaning up {!r}".format(self),
707 ResourceWarning)
Nick Coghlan543af752010-10-24 11:23:25 +0000708
709 def __exit__(self, exc, value, tb):
710 self.cleanup()
711
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000712 def __del__(self):
713 # Issue a ResourceWarning if implicit cleanup needed
714 self.cleanup(_warn=True)
Nick Coghlan543af752010-10-24 11:23:25 +0000715
716 # XXX (ncoghlan): The following code attempts to make
717 # this class tolerant of the module nulling out process
718 # that happens during CPython interpreter shutdown
719 # Alas, it doesn't actually manage it. See issue #10188
720 _listdir = staticmethod(_os.listdir)
721 _path_join = staticmethod(_os.path.join)
722 _isdir = staticmethod(_os.path.isdir)
Charles-François Natalidef35432011-07-29 18:59:24 +0200723 _islink = staticmethod(_os.path.islink)
Nick Coghlan543af752010-10-24 11:23:25 +0000724 _remove = staticmethod(_os.remove)
725 _rmdir = staticmethod(_os.rmdir)
Florent Xicluna68f71a32011-10-28 16:06:23 +0200726 _os_error = OSError
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000727 _warn = _warnings.warn
Nick Coghlan543af752010-10-24 11:23:25 +0000728
729 def _rmtree(self, path):
730 # Essentially a stripped down version of shutil.rmtree. We can't
731 # use globals because they may be None'ed out at shutdown.
732 for name in self._listdir(path):
733 fullname = self._path_join(path, name)
734 try:
Charles-François Natalidef35432011-07-29 18:59:24 +0200735 isdir = self._isdir(fullname) and not self._islink(fullname)
Nick Coghlan543af752010-10-24 11:23:25 +0000736 except self._os_error:
737 isdir = False
738 if isdir:
739 self._rmtree(fullname)
740 else:
741 try:
742 self._remove(fullname)
743 except self._os_error:
744 pass
745 try:
746 self._rmdir(path)
747 except self._os_error:
748 pass