blob: 57e8a829ec00d93b4ca518066628816d7d341329 [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
Guido van Rossum9a634702007-07-09 10:24:45 +000032import io as _io
Guido van Rossum0e548712002-08-09 16:14:33 +000033import os as _os
Serhiy Storchaka99e033b2014-01-27 11:18:27 +020034import shutil as _shutil
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
Serhiy Storchakaa28632b2014-01-27 11:21:54 +020037import weakref as _weakref
Guido van Rossum0e548712002-08-09 16:14:33 +000038
Guido van Rossumd8faa362007-04-27 19:54:29 +000039try:
Georg Brandl2067bfd2008-05-25 13:05:15 +000040 import _thread
Brett Cannoncd171c82013-07-04 17:43:24 -040041except ImportError:
Georg Brandl2067bfd2008-05-25 13:05:15 +000042 import _dummy_thread as _thread
Guido van Rossuma0934242002-12-30 22:36:09 +000043_allocate_lock = _thread.allocate_lock
Guido van Rossum0e548712002-08-09 16:14:33 +000044
45_text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL
Tim Petersa0d55de2002-08-09 18:01:01 +000046if hasattr(_os, 'O_NOFOLLOW'):
47 _text_openflags |= _os.O_NOFOLLOW
Guido van Rossum0e548712002-08-09 16:14:33 +000048
49_bin_openflags = _text_openflags
Tim Petersa0d55de2002-08-09 18:01:01 +000050if hasattr(_os, 'O_BINARY'):
51 _bin_openflags |= _os.O_BINARY
Guido van Rossum0e548712002-08-09 16:14:33 +000052
53if hasattr(_os, 'TMP_MAX'):
54 TMP_MAX = _os.TMP_MAX
55else:
56 TMP_MAX = 10000
57
R David Murray3a420c72011-06-22 21:01:13 -040058# Although it does not have an underscore for historical reasons, this
59# variable is an internal implementation detail (see issue 10354).
Tim Petersbd7b4c72002-08-13 23:33:56 +000060template = "tmp"
Guido van Rossum0e548712002-08-09 16:14:33 +000061
Guido van Rossum0e548712002-08-09 16:14:33 +000062# Internal routines.
63
64_once_lock = _allocate_lock()
65
Guido van Rossumb256159392003-11-10 02:16:36 +000066if hasattr(_os, "lstat"):
67 _stat = _os.lstat
68elif hasattr(_os, "stat"):
69 _stat = _os.stat
70else:
Florent Xicluna68f71a32011-10-28 16:06:23 +020071 # Fallback. All we need is something that raises OSError if the
Guido van Rossumb256159392003-11-10 02:16:36 +000072 # file doesn't exist.
73 def _stat(fn):
Victor Stinnerdaf45552013-08-28 00:53:59 +020074 fd = _os.open(fn, _os.O_RDONLY)
Victor Stinner69b1e262014-03-20 08:50:52 +010075 _os.close(fd)
Guido van Rossumb256159392003-11-10 02:16:36 +000076
77def _exists(fn):
78 try:
79 _stat(fn)
Florent Xicluna68f71a32011-10-28 16:06:23 +020080 except OSError:
Guido van Rossumb256159392003-11-10 02:16:36 +000081 return False
82 else:
83 return True
84
Guido van Rossum0e548712002-08-09 16:14:33 +000085class _RandomNameSequence:
86 """An instance of _RandomNameSequence generates an endless
87 sequence of unpredictable strings which can safely be incorporated
88 into file names. Each string is six characters long. Multiple
89 threads can safely use the same instance at the same time.
90
91 _RandomNameSequence is an iterator."""
92
Raymond Hettinger572895b2010-11-09 03:43:58 +000093 characters = "abcdefghijklmnopqrstuvwxyz0123456789_"
Guido van Rossum0e548712002-08-09 16:14:33 +000094
Antoine Pitrou4558bad2011-11-25 21:28:15 +010095 @property
96 def rng(self):
97 cur_pid = _os.getpid()
98 if cur_pid != getattr(self, '_rng_pid', None):
99 self._rng = _Random()
100 self._rng_pid = cur_pid
101 return self._rng
Tim Peters97701b52002-11-21 15:59:59 +0000102
Guido van Rossum0e548712002-08-09 16:14:33 +0000103 def __iter__(self):
104 return self
105
Georg Brandla18af4e2007-04-21 15:47:16 +0000106 def __next__(self):
Guido van Rossum0e548712002-08-09 16:14:33 +0000107 c = self.characters
Tim Peters97701b52002-11-21 15:59:59 +0000108 choose = self.rng.choice
Victor Stinner97869102013-08-14 01:28:28 +0200109 letters = [choose(c) for dummy in range(8)]
Raymond Hettinger572895b2010-11-09 03:43:58 +0000110 return ''.join(letters)
Guido van Rossum0e548712002-08-09 16:14:33 +0000111
112def _candidate_tempdir_list():
113 """Generate a list of candidate temporary directories which
114 _get_default_tempdir will try."""
115
116 dirlist = []
117
118 # First, try the environment.
119 for envname in 'TMPDIR', 'TEMP', 'TMP':
120 dirname = _os.getenv(envname)
121 if dirname: dirlist.append(dirname)
122
123 # Failing that, try OS-specific locations.
Alexandre Vassalottieca20b62008-05-16 02:54:33 +0000124 if _os.name == 'nt':
Guido van Rossum0e548712002-08-09 16:14:33 +0000125 dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
126 else:
127 dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
128
129 # As a last resort, the current directory.
130 try:
131 dirlist.append(_os.getcwd())
Florent Xicluna68f71a32011-10-28 16:06:23 +0200132 except (AttributeError, OSError):
Guido van Rossum0e548712002-08-09 16:14:33 +0000133 dirlist.append(_os.curdir)
134
135 return dirlist
Tim Petersa0d55de2002-08-09 18:01:01 +0000136
Guido van Rossum0e548712002-08-09 16:14:33 +0000137def _get_default_tempdir():
138 """Calculate the default directory to use for temporary files.
Guido van Rossume888cdc2002-08-17 14:50:24 +0000139 This routine should be called exactly once.
Guido van Rossum0e548712002-08-09 16:14:33 +0000140
141 We determine whether or not a candidate temp dir is usable by
142 trying to create and write to a file in that directory. If this
143 is successful, the test file is deleted. To prevent denial of
144 service, the name of the test file must be randomized."""
145
146 namer = _RandomNameSequence()
147 dirlist = _candidate_tempdir_list()
Guido van Rossum0e548712002-08-09 16:14:33 +0000148
149 for dir in dirlist:
150 if dir != _os.curdir:
Tim Golden6d09f092013-10-25 18:38:16 +0100151 dir = _os.path.abspath(dir)
Guido van Rossum0e548712002-08-09 16:14:33 +0000152 # Try only a few names per directory.
Guido van Rossum805365e2007-05-07 22:24:25 +0000153 for seq in range(100):
Georg Brandla18af4e2007-04-21 15:47:16 +0000154 name = next(namer)
Guido van Rossum0e548712002-08-09 16:14:33 +0000155 filename = _os.path.join(dir, name)
156 try:
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000157 fd = _os.open(filename, _bin_openflags, 0o600)
Serhiy Storchakaf6b361e2013-02-13 00:35:30 +0200158 try:
159 try:
Serhiy Storchaka76a2ed12013-02-13 00:59:26 +0200160 with _io.open(fd, 'wb', closefd=False) as fp:
161 fp.write(b'blat')
Serhiy Storchakaf6b361e2013-02-13 00:35:30 +0200162 finally:
163 _os.close(fd)
164 finally:
165 _os.unlink(filename)
Guido van Rossum0e548712002-08-09 16:14:33 +0000166 return dir
Florent Xicluna68f71a32011-10-28 16:06:23 +0200167 except FileExistsError:
Guido van Rossum0e548712002-08-09 16:14:33 +0000168 pass
Florent Xicluna68f71a32011-10-28 16:06:23 +0200169 except OSError:
170 break # no point trying more names in this directory
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200171 raise FileNotFoundError(_errno.ENOENT,
172 "No usable temporary directory found in %s" %
173 dirlist)
Guido van Rossum0e548712002-08-09 16:14:33 +0000174
Guido van Rossume888cdc2002-08-17 14:50:24 +0000175_name_sequence = None
176
Guido van Rossum0e548712002-08-09 16:14:33 +0000177def _get_candidate_names():
178 """Common setup sequence for all user-callable interfaces."""
179
Guido van Rossume888cdc2002-08-17 14:50:24 +0000180 global _name_sequence
181 if _name_sequence is None:
182 _once_lock.acquire()
183 try:
184 if _name_sequence is None:
185 _name_sequence = _RandomNameSequence()
186 finally:
187 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000188 return _name_sequence
Guido van Rossum41f95031992-03-31 19:02:01 +0000189
190
Guido van Rossum0e548712002-08-09 16:14:33 +0000191def _mkstemp_inner(dir, pre, suf, flags):
192 """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
Tim Peters9fadfb02001-01-13 03:04:02 +0000193
Guido van Rossum0e548712002-08-09 16:14:33 +0000194 names = _get_candidate_names()
195
Guido van Rossum805365e2007-05-07 22:24:25 +0000196 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000197 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000198 file = _os.path.join(dir, pre + name + suf)
199 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000200 fd = _os.open(file, flags, 0o600)
Martin v. Löwisd6625482003-10-12 17:37:01 +0000201 return (fd, _os.path.abspath(file))
Florent Xicluna68f71a32011-10-28 16:06:23 +0200202 except FileExistsError:
203 continue # try again
Eli Benderskyf315df32013-09-06 06:11:19 -0700204 except PermissionError:
205 # This exception is thrown when a directory with the chosen name
206 # already exists on windows.
207 if _os.name == 'nt':
208 continue
209 else:
210 raise
Guido van Rossum0e548712002-08-09 16:14:33 +0000211
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200212 raise FileExistsError(_errno.EEXIST,
213 "No usable temporary file name found")
Tim Petersa0d55de2002-08-09 18:01:01 +0000214
Guido van Rossum0e548712002-08-09 16:14:33 +0000215
216# User visible interfaces.
Guido van Rossumb0e57181998-10-14 20:27:05 +0000217
Guido van Rossum41f95031992-03-31 19:02:01 +0000218def gettempprefix():
Guido van Rossum0e548712002-08-09 16:14:33 +0000219 """Accessor for tempdir.template."""
220 return template
Tim Peters9fadfb02001-01-13 03:04:02 +0000221
Guido van Rossume888cdc2002-08-17 14:50:24 +0000222tempdir = None
223
Guido van Rossum0e548712002-08-09 16:14:33 +0000224def gettempdir():
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000225 """Accessor for tempfile.tempdir."""
Guido van Rossume888cdc2002-08-17 14:50:24 +0000226 global tempdir
227 if tempdir is None:
228 _once_lock.acquire()
229 try:
230 if tempdir is None:
231 tempdir = _get_default_tempdir()
232 finally:
233 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000234 return tempdir
235
Guido van Rossume888cdc2002-08-17 14:50:24 +0000236def mkstemp(suffix="", prefix=template, dir=None, text=False):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000237 """User-callable function to create and return a unique temporary
Guido van Rossum0e548712002-08-09 16:14:33 +0000238 file. The return value is a pair (fd, name) where fd is the
239 file descriptor returned by os.open, and name is the filename.
240
241 If 'suffix' is specified, the file name will end with that suffix,
242 otherwise there will be no suffix.
243
244 If 'prefix' is specified, the file name will begin with that prefix,
245 otherwise a default prefix is used.
246
247 If 'dir' is specified, the file will be created in that directory,
248 otherwise a default directory is used.
249
Tim Peters04490bf2002-08-14 15:41:26 +0000250 If 'text' is specified and true, the file is opened in text
251 mode. Else (the default) the file is opened in binary mode. On
252 some operating systems, this makes no difference.
Guido van Rossum0e548712002-08-09 16:14:33 +0000253
254 The file is readable and writable only by the creating user ID.
255 If the operating system uses permission bits to indicate whether a
256 file is executable, the file is executable by no one. The file
257 descriptor is not inherited by children of this process.
258
259 Caller is responsible for deleting the file when done with it.
Tim Peters9fadfb02001-01-13 03:04:02 +0000260 """
261
Guido van Rossume888cdc2002-08-17 14:50:24 +0000262 if dir is None:
263 dir = gettempdir()
264
Tim Peters04490bf2002-08-14 15:41:26 +0000265 if text:
Guido van Rossum0e548712002-08-09 16:14:33 +0000266 flags = _text_openflags
Tim Peters04490bf2002-08-14 15:41:26 +0000267 else:
268 flags = _bin_openflags
Guido van Rossum0e548712002-08-09 16:14:33 +0000269
270 return _mkstemp_inner(dir, prefix, suffix, flags)
Guido van Rossumcff34541992-01-14 18:31:56 +0000271
Guido van Rossumeee94981991-11-12 15:38:08 +0000272
Guido van Rossume888cdc2002-08-17 14:50:24 +0000273def mkdtemp(suffix="", prefix=template, dir=None):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000274 """User-callable function to create and return a unique temporary
Guido van Rossum0e548712002-08-09 16:14:33 +0000275 directory. The return value is the pathname of the directory.
276
Tim Peters04490bf2002-08-14 15:41:26 +0000277 Arguments are as for mkstemp, except that the 'text' argument is
Guido van Rossum0e548712002-08-09 16:14:33 +0000278 not accepted.
279
280 The directory is readable, writable, and searchable only by the
281 creating user.
282
283 Caller is responsible for deleting the directory when done with it.
284 """
285
Guido van Rossume888cdc2002-08-17 14:50:24 +0000286 if dir is None:
287 dir = gettempdir()
288
Guido van Rossum0e548712002-08-09 16:14:33 +0000289 names = _get_candidate_names()
Tim Petersa0d55de2002-08-09 18:01:01 +0000290
Guido van Rossum805365e2007-05-07 22:24:25 +0000291 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000292 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000293 file = _os.path.join(dir, prefix + name + suffix)
294 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000295 _os.mkdir(file, 0o700)
Guido van Rossum0e548712002-08-09 16:14:33 +0000296 return file
Florent Xicluna68f71a32011-10-28 16:06:23 +0200297 except FileExistsError:
298 continue # try again
Guido van Rossum0e548712002-08-09 16:14:33 +0000299
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200300 raise FileExistsError(_errno.EEXIST,
301 "No usable temporary directory name found")
Guido van Rossum0e548712002-08-09 16:14:33 +0000302
Guido van Rossume888cdc2002-08-17 14:50:24 +0000303def mktemp(suffix="", prefix=template, dir=None):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000304 """User-callable function to return a unique temporary file name. The
Guido van Rossum0e548712002-08-09 16:14:33 +0000305 file is not created.
306
Tim Peters04490bf2002-08-14 15:41:26 +0000307 Arguments are as for mkstemp, except that the 'text' argument is
Guido van Rossum0e548712002-08-09 16:14:33 +0000308 not accepted.
309
310 This function is unsafe and should not be used. The file name
311 refers to a file that did not exist at some point, but by the time
312 you get around to creating it, someone else may have beaten you to
313 the punch.
314 """
315
Guido van Rossum44f602d2002-11-22 15:56:29 +0000316## from warnings import warn as _warn
317## _warn("mktemp is a potential security risk to your program",
318## RuntimeWarning, stacklevel=2)
Guido van Rossum0e548712002-08-09 16:14:33 +0000319
Guido van Rossume888cdc2002-08-17 14:50:24 +0000320 if dir is None:
321 dir = gettempdir()
322
Guido van Rossum0e548712002-08-09 16:14:33 +0000323 names = _get_candidate_names()
Guido van Rossum805365e2007-05-07 22:24:25 +0000324 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000325 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000326 file = _os.path.join(dir, prefix + name + suffix)
Guido van Rossumb256159392003-11-10 02:16:36 +0000327 if not _exists(file):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000328 return file
Guido van Rossumca549821997-08-12 18:00:12 +0000329
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200330 raise FileExistsError(_errno.EEXIST,
331 "No usable temporary filename found")
Guido van Rossumca549821997-08-12 18:00:12 +0000332
Christian Heimes3ecfea712008-02-09 20:51:34 +0000333
Antoine Pitrou17c93262013-12-21 22:14:56 +0100334class _TemporaryFileCloser:
335 """A separate object allowing proper closing of a temporary file's
336 underlying file object, without adding a __del__ method to the
337 temporary file."""
Tim Petersa255a722001-12-18 22:32:40 +0000338
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200339 file = None # Set here since __del__ checks it
Serhiy Storchaka99e033b2014-01-27 11:18:27 +0200340 close_called = False
341
Guido van Rossumd8faa362007-04-27 19:54:29 +0000342 def __init__(self, file, name, delete=True):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000343 self.file = file
Guido van Rossum0e548712002-08-09 16:14:33 +0000344 self.name = name
Guido van Rossumd8faa362007-04-27 19:54:29 +0000345 self.delete = delete
Guido van Rossumca549821997-08-12 18:00:12 +0000346
Guido van Rossum0e548712002-08-09 16:14:33 +0000347 # NT provides delete-on-close as a primitive, so we don't need
348 # the wrapper to do anything special. We still use it so that
349 # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
350 if _os.name != 'nt':
Guido van Rossum0e548712002-08-09 16:14:33 +0000351 # Cache the unlinker so we don't get spurious errors at
352 # shutdown when the module-level "os" is None'd out. Note
353 # that this must be referenced as self.unlink, because the
354 # name TemporaryFileWrapper may also get None'd out before
355 # __del__ is called.
Tim Peters1baa22a2001-01-12 10:02:46 +0000356
Serhiy Storchaka99e033b2014-01-27 11:18:27 +0200357 def close(self, unlink=_os.unlink):
358 if not self.close_called and self.file is not None:
Tim Peters6ef966e2002-11-21 15:48:33 +0000359 self.close_called = True
Guido van Rossum0e548712002-08-09 16:14:33 +0000360 self.file.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000361 if self.delete:
Serhiy Storchaka99e033b2014-01-27 11:18:27 +0200362 unlink(self.name)
Tim Peters1baa22a2001-01-12 10:02:46 +0000363
Antoine Pitrou17c93262013-12-21 22:14:56 +0100364 # Need to ensure the file is deleted on __del__
Guido van Rossum0e548712002-08-09 16:14:33 +0000365 def __del__(self):
366 self.close()
Tim Peters1baa22a2001-01-12 10:02:46 +0000367
Benjamin Peterson98d23f22009-06-30 22:27:25 +0000368 else:
Antoine Pitrou17c93262013-12-21 22:14:56 +0100369 def close(self):
370 if not self.close_called:
371 self.close_called = True
372 self.file.close()
373
374
375class _TemporaryFileWrapper:
376 """Temporary file wrapper
377
378 This class provides a wrapper around files opened for
379 temporary use. In particular, it seeks to automatically
380 remove the file when it is no longer needed.
381 """
382
383 def __init__(self, file, name, delete=True):
384 self.file = file
385 self.name = name
386 self.delete = delete
387 self._closer = _TemporaryFileCloser(file, name, delete)
388
389 def __getattr__(self, name):
390 # Attribute lookups are delegated to the underlying file
391 # and cached for non-numeric results
392 # (i.e. methods are cached, closed and friends are not)
393 file = self.__dict__['file']
394 a = getattr(file, name)
395 if hasattr(a, '__call__'):
396 func = a
397 @_functools.wraps(func)
398 def func_wrapper(*args, **kwargs):
399 return func(*args, **kwargs)
400 # Avoid closing the file as long as the wrapper is alive,
401 # see issue #18879.
402 func_wrapper._closer = self._closer
403 a = func_wrapper
404 if not isinstance(a, int):
405 setattr(self, name, a)
406 return a
407
408 # The underlying __enter__ method returns the wrong object
409 # (self.file) so override it to return the wrapper
410 def __enter__(self):
411 self.file.__enter__()
412 return self
413
414 # Need to trap __exit__ as well to ensure the file gets
415 # deleted when used in a with statement
416 def __exit__(self, exc, value, tb):
417 result = self.file.__exit__(exc, value, tb)
418 self.close()
419 return result
420
421 def close(self):
422 """
423 Close the temporary file, possibly deleting it.
424 """
425 self._closer.close()
426
427 # iter() doesn't use __getattr__ to find the __iter__ method
428 def __iter__(self):
429 return iter(self.file)
Christian Heimes3ecfea712008-02-09 20:51:34 +0000430
431
Guido van Rossumf0c74162007-08-28 03:29:45 +0000432def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None,
433 newline=None, suffix="", prefix=template,
434 dir=None, delete=True):
Guido van Rossum0e548712002-08-09 16:14:33 +0000435 """Create and return a temporary file.
436 Arguments:
437 'prefix', 'suffix', 'dir' -- as for mkstemp.
Guido van Rossumf0c74162007-08-28 03:29:45 +0000438 'mode' -- the mode argument to io.open (default "w+b").
439 'buffering' -- the buffer size argument to io.open (default -1).
440 'encoding' -- the encoding argument to io.open (default None)
441 'newline' -- the newline argument to io.open (default None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000442 'delete' -- whether the file is deleted on close (default True).
Guido van Rossum0e548712002-08-09 16:14:33 +0000443 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000444
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000445 Returns an object with a file-like interface; the name of the file
446 is accessible as file.name. The file will be automatically deleted
Guido van Rossumd8faa362007-04-27 19:54:29 +0000447 when it is closed unless the 'delete' argument is set to False.
Guido van Rossum0e548712002-08-09 16:14:33 +0000448 """
Tim Peters1baa22a2001-01-12 10:02:46 +0000449
Guido van Rossume888cdc2002-08-17 14:50:24 +0000450 if dir is None:
451 dir = gettempdir()
452
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000453 flags = _bin_openflags
Tim Peters1baa22a2001-01-12 10:02:46 +0000454
Guido van Rossum0e548712002-08-09 16:14:33 +0000455 # Setting O_TEMPORARY in the flags causes the OS to delete
456 # the file when it is closed. This is only supported by Windows.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000457 if _os.name == 'nt' and delete:
Guido van Rossum0e548712002-08-09 16:14:33 +0000458 flags |= _os.O_TEMPORARY
Tim Peters1baa22a2001-01-12 10:02:46 +0000459
Guido van Rossum0e548712002-08-09 16:14:33 +0000460 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000461 file = _io.open(fd, mode, buffering=buffering,
462 newline=newline, encoding=encoding)
463
Guido van Rossumd8faa362007-04-27 19:54:29 +0000464 return _TemporaryFileWrapper(file, name, delete)
Guido van Rossum0e548712002-08-09 16:14:33 +0000465
Jason Tishler80c02af2002-08-14 15:10:09 +0000466if _os.name != 'posix' or _os.sys.platform == 'cygwin':
467 # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
468 # while it is open.
Guido van Rossum0e548712002-08-09 16:14:33 +0000469 TemporaryFile = NamedTemporaryFile
Tim Peters1baa22a2001-01-12 10:02:46 +0000470
471else:
Guido van Rossumf0c74162007-08-28 03:29:45 +0000472 def TemporaryFile(mode='w+b', buffering=-1, encoding=None,
473 newline=None, suffix="", prefix=template,
474 dir=None):
Guido van Rossum0e548712002-08-09 16:14:33 +0000475 """Create and return a temporary file.
476 Arguments:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000477 'prefix', 'suffix', 'dir' -- as for mkstemp.
Guido van Rossumf0c74162007-08-28 03:29:45 +0000478 'mode' -- the mode argument to io.open (default "w+b").
479 'buffering' -- the buffer size argument to io.open (default -1).
480 'encoding' -- the encoding argument to io.open (default None)
481 'newline' -- the newline argument to io.open (default None)
Guido van Rossum0e548712002-08-09 16:14:33 +0000482 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000483
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000484 Returns an object with a file-like interface. The file has no
485 name, and will cease to exist when it is closed.
Guido van Rossum0e548712002-08-09 16:14:33 +0000486 """
487
Guido van Rossume888cdc2002-08-17 14:50:24 +0000488 if dir is None:
489 dir = gettempdir()
490
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000491 flags = _bin_openflags
Guido van Rossum0e548712002-08-09 16:14:33 +0000492
493 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
494 try:
495 _os.unlink(name)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000496 return _io.open(fd, mode, buffering=buffering,
497 newline=newline, encoding=encoding)
Guido van Rossum0e548712002-08-09 16:14:33 +0000498 except:
499 _os.close(fd)
500 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +0000501
502class SpooledTemporaryFile:
Serhiy Storchaka4f169a72013-02-09 11:46:42 +0200503 """Temporary file wrapper, specialized to switch from BytesIO
504 or StringIO to a real file when it exceeds a certain size or
Guido van Rossumd8faa362007-04-27 19:54:29 +0000505 when a fileno is needed.
506 """
507 _rolled = False
508
Guido van Rossumf0c74162007-08-28 03:29:45 +0000509 def __init__(self, max_size=0, mode='w+b', buffering=-1,
510 encoding=None, newline=None,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000511 suffix="", prefix=template, dir=None):
Guido van Rossum9a634702007-07-09 10:24:45 +0000512 if 'b' in mode:
513 self._file = _io.BytesIO()
514 else:
Guido van Rossum5d212552007-10-29 16:42:51 +0000515 # Setting newline="\n" avoids newline translation;
516 # this is important because otherwise on Windows we'd
Guido van Rossum98297ee2007-11-06 21:34:58 +0000517 # hget double newline translation upon rollover().
Alexandre Vassalotti3ade6f92008-06-12 01:13:54 +0000518 self._file = _io.StringIO(newline="\n")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000519 self._max_size = max_size
520 self._rolled = False
Guido van Rossumf0c74162007-08-28 03:29:45 +0000521 self._TemporaryFileArgs = {'mode': mode, 'buffering': buffering,
522 'suffix': suffix, 'prefix': prefix,
523 'encoding': encoding, 'newline': newline,
524 'dir': dir}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000525
526 def _check(self, file):
527 if self._rolled: return
528 max_size = self._max_size
529 if max_size and file.tell() > max_size:
530 self.rollover()
531
532 def rollover(self):
533 if self._rolled: return
534 file = self._file
Guido van Rossumf0c74162007-08-28 03:29:45 +0000535 newfile = self._file = TemporaryFile(**self._TemporaryFileArgs)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000536 del self._TemporaryFileArgs
537
538 newfile.write(file.getvalue())
539 newfile.seek(file.tell(), 0)
540
541 self._rolled = True
542
Christian Heimes3ecfea712008-02-09 20:51:34 +0000543 # The method caching trick from NamedTemporaryFile
544 # won't work here, because _file may change from a
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300545 # BytesIO/StringIO instance to a real file. So we list
Christian Heimes3ecfea712008-02-09 20:51:34 +0000546 # all the methods directly.
547
548 # Context management protocol
549 def __enter__(self):
550 if self._file.closed:
551 raise ValueError("Cannot enter context with closed file")
552 return self
553
554 def __exit__(self, exc, value, tb):
555 self._file.close()
556
Guido van Rossumd8faa362007-04-27 19:54:29 +0000557 # file protocol
558 def __iter__(self):
559 return self._file.__iter__()
560
561 def close(self):
562 self._file.close()
563
564 @property
565 def closed(self):
566 return self._file.closed
567
568 @property
569 def encoding(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200570 try:
571 return self._file.encoding
572 except AttributeError:
573 if 'b' in self._TemporaryFileArgs['mode']:
574 raise
575 return self._TemporaryFileArgs['encoding']
Guido van Rossumd8faa362007-04-27 19:54:29 +0000576
577 def fileno(self):
578 self.rollover()
579 return self._file.fileno()
580
581 def flush(self):
582 self._file.flush()
583
584 def isatty(self):
585 return self._file.isatty()
586
587 @property
588 def mode(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200589 try:
590 return self._file.mode
591 except AttributeError:
592 return self._TemporaryFileArgs['mode']
Guido van Rossumd8faa362007-04-27 19:54:29 +0000593
594 @property
595 def name(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200596 try:
597 return self._file.name
598 except AttributeError:
599 return None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000600
601 @property
602 def newlines(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200603 try:
604 return self._file.newlines
605 except AttributeError:
606 if 'b' in self._TemporaryFileArgs['mode']:
607 raise
608 return self._TemporaryFileArgs['newline']
Guido van Rossumd8faa362007-04-27 19:54:29 +0000609
610 def read(self, *args):
611 return self._file.read(*args)
612
613 def readline(self, *args):
614 return self._file.readline(*args)
615
616 def readlines(self, *args):
617 return self._file.readlines(*args)
618
619 def seek(self, *args):
620 self._file.seek(*args)
621
622 @property
623 def softspace(self):
624 return self._file.softspace
625
626 def tell(self):
627 return self._file.tell()
628
Antoine Pitrou0e86a582011-11-25 18:03:09 +0100629 def truncate(self, size=None):
630 if size is None:
631 self._file.truncate()
632 else:
633 if size > self._max_size:
634 self.rollover()
635 self._file.truncate(size)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000636
637 def write(self, s):
638 file = self._file
639 rv = file.write(s)
640 self._check(file)
641 return rv
642
643 def writelines(self, iterable):
644 file = self._file
645 rv = file.writelines(iterable)
646 self._check(file)
647 return rv
648
Nick Coghlan543af752010-10-24 11:23:25 +0000649
650class TemporaryDirectory(object):
651 """Create and return a temporary directory. This has the same
652 behavior as mkdtemp but can be used as a context manager. For
653 example:
654
655 with TemporaryDirectory() as tmpdir:
656 ...
657
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300658 Upon exiting the context, the directory and everything contained
Nick Coghlan543af752010-10-24 11:23:25 +0000659 in it are removed.
660 """
661
Serhiy Storchaka99e033b2014-01-27 11:18:27 +0200662 # Handle mkdtemp raising an exception
663 name = None
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200664 _finalizer = None
Serhiy Storchaka99e033b2014-01-27 11:18:27 +0200665 _closed = False
666
Nick Coghlan543af752010-10-24 11:23:25 +0000667 def __init__(self, suffix="", prefix=template, dir=None):
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000668 self.name = mkdtemp(suffix, prefix, dir)
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200669 self._finalizer = _weakref.finalize(
670 self, self._cleanup, self.name,
671 warn_message="Implicitly cleaning up {!r}".format(self))
672
673 @classmethod
674 def _cleanup(cls, name, warn_message=None):
675 _shutil.rmtree(name)
676 if warn_message is not None:
677 _warnings.warn(warn_message, ResourceWarning)
678
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000679
680 def __repr__(self):
681 return "<{} {!r}>".format(self.__class__.__name__, self.name)
Nick Coghlan543af752010-10-24 11:23:25 +0000682
683 def __enter__(self):
684 return self.name
685
Nick Coghlan543af752010-10-24 11:23:25 +0000686 def __exit__(self, exc, value, tb):
687 self.cleanup()
688
Serhiy Storchakaa28632b2014-01-27 11:21:54 +0200689 def cleanup(self):
690 if self._finalizer is not None:
691 self._finalizer.detach()
692 if self.name is not None and not self._closed:
693 _shutil.rmtree(self.name)
694 self._closed = True