blob: 91332b61be72e605b1dd36deaef5a3c789329a21 [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
Nick Coghlan6b22f3f2010-12-12 15:24:21 +000030import warnings as _warnings
31import sys as _sys
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 Storchaka7451a722013-02-09 22:25:49 +020034import errno as _errno
Guido van Rossum0e548712002-08-09 16:14:33 +000035from random import Random as _Random
36
Guido van Rossumd8faa362007-04-27 19:54:29 +000037try:
Guido van Rossum0e548712002-08-09 16:14:33 +000038 import fcntl as _fcntl
Tim Peters90ee7eb2004-07-18 23:58:17 +000039except ImportError:
Tim Peters291f14e2003-07-22 02:50:01 +000040 def _set_cloexec(fd):
41 pass
42else:
Guido van Rossum0e548712002-08-09 16:14:33 +000043 def _set_cloexec(fd):
Tim Peters90ee7eb2004-07-18 23:58:17 +000044 try:
45 flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0)
Florent Xicluna68f71a32011-10-28 16:06:23 +020046 except OSError:
Tim Peters90ee7eb2004-07-18 23:58:17 +000047 pass
Alex Martellif09994e2003-11-09 16:44:09 +000048 else:
Guido van Rossum0e548712002-08-09 16:14:33 +000049 # flags read successfully, modify
50 flags |= _fcntl.FD_CLOEXEC
51 _fcntl.fcntl(fd, _fcntl.F_SETFD, flags)
Tim Peters291f14e2003-07-22 02:50:01 +000052
Guido van Rossum0e548712002-08-09 16:14:33 +000053
54try:
Georg Brandl2067bfd2008-05-25 13:05:15 +000055 import _thread
Guido van Rossuma0934242002-12-30 22:36:09 +000056except ImportError:
Georg Brandl2067bfd2008-05-25 13:05:15 +000057 import _dummy_thread as _thread
Guido van Rossuma0934242002-12-30 22:36:09 +000058_allocate_lock = _thread.allocate_lock
Guido van Rossum0e548712002-08-09 16:14:33 +000059
60_text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL
Tim Petersa0d55de2002-08-09 18:01:01 +000061if hasattr(_os, 'O_NOINHERIT'):
62 _text_openflags |= _os.O_NOINHERIT
63if hasattr(_os, 'O_NOFOLLOW'):
64 _text_openflags |= _os.O_NOFOLLOW
Guido van Rossum0e548712002-08-09 16:14:33 +000065
66_bin_openflags = _text_openflags
Tim Petersa0d55de2002-08-09 18:01:01 +000067if hasattr(_os, 'O_BINARY'):
68 _bin_openflags |= _os.O_BINARY
Guido van Rossum0e548712002-08-09 16:14:33 +000069
70if hasattr(_os, 'TMP_MAX'):
71 TMP_MAX = _os.TMP_MAX
72else:
73 TMP_MAX = 10000
74
R David Murray3a420c72011-06-22 21:01:13 -040075# Although it does not have an underscore for historical reasons, this
76# variable is an internal implementation detail (see issue 10354).
Tim Petersbd7b4c72002-08-13 23:33:56 +000077template = "tmp"
Guido van Rossum0e548712002-08-09 16:14:33 +000078
Guido van Rossum0e548712002-08-09 16:14:33 +000079# Internal routines.
80
81_once_lock = _allocate_lock()
82
Guido van Rossumb256159392003-11-10 02:16:36 +000083if hasattr(_os, "lstat"):
84 _stat = _os.lstat
85elif hasattr(_os, "stat"):
86 _stat = _os.stat
87else:
Florent Xicluna68f71a32011-10-28 16:06:23 +020088 # Fallback. All we need is something that raises OSError if the
Guido van Rossumb256159392003-11-10 02:16:36 +000089 # file doesn't exist.
90 def _stat(fn):
Florent Xicluna46f5d142011-10-28 21:58:56 +020091 f = open(fn)
Guido van Rossumb256159392003-11-10 02:16:36 +000092 f.close()
93
94def _exists(fn):
95 try:
96 _stat(fn)
Florent Xicluna68f71a32011-10-28 16:06:23 +020097 except OSError:
Guido van Rossumb256159392003-11-10 02:16:36 +000098 return False
99 else:
100 return True
101
Guido van Rossum0e548712002-08-09 16:14:33 +0000102class _RandomNameSequence:
103 """An instance of _RandomNameSequence generates an endless
104 sequence of unpredictable strings which can safely be incorporated
105 into file names. Each string is six characters long. Multiple
106 threads can safely use the same instance at the same time.
107
108 _RandomNameSequence is an iterator."""
109
Raymond Hettinger572895b2010-11-09 03:43:58 +0000110 characters = "abcdefghijklmnopqrstuvwxyz0123456789_"
Guido van Rossum0e548712002-08-09 16:14:33 +0000111
Antoine Pitrou4558bad2011-11-25 21:28:15 +0100112 @property
113 def rng(self):
114 cur_pid = _os.getpid()
115 if cur_pid != getattr(self, '_rng_pid', None):
116 self._rng = _Random()
117 self._rng_pid = cur_pid
118 return self._rng
Tim Peters97701b52002-11-21 15:59:59 +0000119
Guido van Rossum0e548712002-08-09 16:14:33 +0000120 def __iter__(self):
121 return self
122
Georg Brandla18af4e2007-04-21 15:47:16 +0000123 def __next__(self):
Guido van Rossum0e548712002-08-09 16:14:33 +0000124 c = self.characters
Tim Peters97701b52002-11-21 15:59:59 +0000125 choose = self.rng.choice
Raymond Hettinger572895b2010-11-09 03:43:58 +0000126 letters = [choose(c) for dummy in "123456"]
127 return ''.join(letters)
Guido van Rossum0e548712002-08-09 16:14:33 +0000128
129def _candidate_tempdir_list():
130 """Generate a list of candidate temporary directories which
131 _get_default_tempdir will try."""
132
133 dirlist = []
134
135 # First, try the environment.
136 for envname in 'TMPDIR', 'TEMP', 'TMP':
137 dirname = _os.getenv(envname)
138 if dirname: dirlist.append(dirname)
139
140 # Failing that, try OS-specific locations.
Alexandre Vassalottieca20b62008-05-16 02:54:33 +0000141 if _os.name == 'nt':
Guido van Rossum0e548712002-08-09 16:14:33 +0000142 dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
143 else:
144 dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
145
146 # As a last resort, the current directory.
147 try:
148 dirlist.append(_os.getcwd())
Florent Xicluna68f71a32011-10-28 16:06:23 +0200149 except (AttributeError, OSError):
Guido van Rossum0e548712002-08-09 16:14:33 +0000150 dirlist.append(_os.curdir)
151
152 return dirlist
Tim Petersa0d55de2002-08-09 18:01:01 +0000153
Guido van Rossum0e548712002-08-09 16:14:33 +0000154def _get_default_tempdir():
155 """Calculate the default directory to use for temporary files.
Guido van Rossume888cdc2002-08-17 14:50:24 +0000156 This routine should be called exactly once.
Guido van Rossum0e548712002-08-09 16:14:33 +0000157
158 We determine whether or not a candidate temp dir is usable by
159 trying to create and write to a file in that directory. If this
160 is successful, the test file is deleted. To prevent denial of
161 service, the name of the test file must be randomized."""
162
163 namer = _RandomNameSequence()
164 dirlist = _candidate_tempdir_list()
Guido van Rossum0e548712002-08-09 16:14:33 +0000165
166 for dir in dirlist:
167 if dir != _os.curdir:
168 dir = _os.path.normcase(_os.path.abspath(dir))
169 # Try only a few names per directory.
Guido van Rossum805365e2007-05-07 22:24:25 +0000170 for seq in range(100):
Georg Brandla18af4e2007-04-21 15:47:16 +0000171 name = next(namer)
Guido van Rossum0e548712002-08-09 16:14:33 +0000172 filename = _os.path.join(dir, name)
173 try:
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000174 fd = _os.open(filename, _bin_openflags, 0o600)
Serhiy Storchakaf6b361e2013-02-13 00:35:30 +0200175 try:
176 try:
Serhiy Storchaka76a2ed12013-02-13 00:59:26 +0200177 with _io.open(fd, 'wb', closefd=False) as fp:
178 fp.write(b'blat')
Serhiy Storchakaf6b361e2013-02-13 00:35:30 +0200179 finally:
180 _os.close(fd)
181 finally:
182 _os.unlink(filename)
Guido van Rossum0e548712002-08-09 16:14:33 +0000183 return dir
Florent Xicluna68f71a32011-10-28 16:06:23 +0200184 except FileExistsError:
Guido van Rossum0e548712002-08-09 16:14:33 +0000185 pass
Florent Xicluna68f71a32011-10-28 16:06:23 +0200186 except OSError:
187 break # no point trying more names in this directory
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200188 raise FileNotFoundError(_errno.ENOENT,
189 "No usable temporary directory found in %s" %
190 dirlist)
Guido van Rossum0e548712002-08-09 16:14:33 +0000191
Guido van Rossume888cdc2002-08-17 14:50:24 +0000192_name_sequence = None
193
Guido van Rossum0e548712002-08-09 16:14:33 +0000194def _get_candidate_names():
195 """Common setup sequence for all user-callable interfaces."""
196
Guido van Rossume888cdc2002-08-17 14:50:24 +0000197 global _name_sequence
198 if _name_sequence is None:
199 _once_lock.acquire()
200 try:
201 if _name_sequence is None:
202 _name_sequence = _RandomNameSequence()
203 finally:
204 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000205 return _name_sequence
Guido van Rossum41f95031992-03-31 19:02:01 +0000206
207
Guido van Rossum0e548712002-08-09 16:14:33 +0000208def _mkstemp_inner(dir, pre, suf, flags):
209 """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
Tim Peters9fadfb02001-01-13 03:04:02 +0000210
Guido van Rossum0e548712002-08-09 16:14:33 +0000211 names = _get_candidate_names()
212
Guido van Rossum805365e2007-05-07 22:24:25 +0000213 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000214 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000215 file = _os.path.join(dir, pre + name + suf)
216 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000217 fd = _os.open(file, flags, 0o600)
Guido van Rossum0e548712002-08-09 16:14:33 +0000218 _set_cloexec(fd)
Martin v. Löwisd6625482003-10-12 17:37:01 +0000219 return (fd, _os.path.abspath(file))
Florent Xicluna68f71a32011-10-28 16:06:23 +0200220 except FileExistsError:
221 continue # try again
Eli Benderskyf315df32013-09-06 06:11:19 -0700222 except PermissionError:
223 # This exception is thrown when a directory with the chosen name
224 # already exists on windows.
225 if _os.name == 'nt':
226 continue
227 else:
228 raise
Guido van Rossum0e548712002-08-09 16:14:33 +0000229
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200230 raise FileExistsError(_errno.EEXIST,
231 "No usable temporary file name found")
Tim Petersa0d55de2002-08-09 18:01:01 +0000232
Guido van Rossum0e548712002-08-09 16:14:33 +0000233
234# User visible interfaces.
Guido van Rossumb0e57181998-10-14 20:27:05 +0000235
Guido van Rossum41f95031992-03-31 19:02:01 +0000236def gettempprefix():
Guido van Rossum0e548712002-08-09 16:14:33 +0000237 """Accessor for tempdir.template."""
238 return template
Tim Peters9fadfb02001-01-13 03:04:02 +0000239
Guido van Rossume888cdc2002-08-17 14:50:24 +0000240tempdir = None
241
Guido van Rossum0e548712002-08-09 16:14:33 +0000242def gettempdir():
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000243 """Accessor for tempfile.tempdir."""
Guido van Rossume888cdc2002-08-17 14:50:24 +0000244 global tempdir
245 if tempdir is None:
246 _once_lock.acquire()
247 try:
248 if tempdir is None:
249 tempdir = _get_default_tempdir()
250 finally:
251 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000252 return tempdir
253
Guido van Rossume888cdc2002-08-17 14:50:24 +0000254def mkstemp(suffix="", prefix=template, dir=None, text=False):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000255 """User-callable function to create and return a unique temporary
Guido van Rossum0e548712002-08-09 16:14:33 +0000256 file. The return value is a pair (fd, name) where fd is the
257 file descriptor returned by os.open, and name is the filename.
258
259 If 'suffix' is specified, the file name will end with that suffix,
260 otherwise there will be no suffix.
261
262 If 'prefix' is specified, the file name will begin with that prefix,
263 otherwise a default prefix is used.
264
265 If 'dir' is specified, the file will be created in that directory,
266 otherwise a default directory is used.
267
Tim Peters04490bf2002-08-14 15:41:26 +0000268 If 'text' is specified and true, the file is opened in text
269 mode. Else (the default) the file is opened in binary mode. On
270 some operating systems, this makes no difference.
Guido van Rossum0e548712002-08-09 16:14:33 +0000271
272 The file is readable and writable only by the creating user ID.
273 If the operating system uses permission bits to indicate whether a
274 file is executable, the file is executable by no one. The file
275 descriptor is not inherited by children of this process.
276
277 Caller is responsible for deleting the file when done with it.
Tim Peters9fadfb02001-01-13 03:04:02 +0000278 """
279
Guido van Rossume888cdc2002-08-17 14:50:24 +0000280 if dir is None:
281 dir = gettempdir()
282
Tim Peters04490bf2002-08-14 15:41:26 +0000283 if text:
Guido van Rossum0e548712002-08-09 16:14:33 +0000284 flags = _text_openflags
Tim Peters04490bf2002-08-14 15:41:26 +0000285 else:
286 flags = _bin_openflags
Guido van Rossum0e548712002-08-09 16:14:33 +0000287
288 return _mkstemp_inner(dir, prefix, suffix, flags)
Guido van Rossumcff34541992-01-14 18:31:56 +0000289
Guido van Rossumeee94981991-11-12 15:38:08 +0000290
Guido van Rossume888cdc2002-08-17 14:50:24 +0000291def mkdtemp(suffix="", prefix=template, dir=None):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000292 """User-callable function to create and return a unique temporary
Guido van Rossum0e548712002-08-09 16:14:33 +0000293 directory. The return value is the pathname of the directory.
294
Tim Peters04490bf2002-08-14 15:41:26 +0000295 Arguments are as for mkstemp, except that the 'text' argument is
Guido van Rossum0e548712002-08-09 16:14:33 +0000296 not accepted.
297
298 The directory is readable, writable, and searchable only by the
299 creating user.
300
301 Caller is responsible for deleting the directory when done with it.
302 """
303
Guido van Rossume888cdc2002-08-17 14:50:24 +0000304 if dir is None:
305 dir = gettempdir()
306
Guido van Rossum0e548712002-08-09 16:14:33 +0000307 names = _get_candidate_names()
Tim Petersa0d55de2002-08-09 18:01:01 +0000308
Guido van Rossum805365e2007-05-07 22:24:25 +0000309 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000310 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000311 file = _os.path.join(dir, prefix + name + suffix)
312 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000313 _os.mkdir(file, 0o700)
Guido van Rossum0e548712002-08-09 16:14:33 +0000314 return file
Florent Xicluna68f71a32011-10-28 16:06:23 +0200315 except FileExistsError:
316 continue # try again
Guido van Rossum0e548712002-08-09 16:14:33 +0000317
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200318 raise FileExistsError(_errno.EEXIST,
319 "No usable temporary directory name found")
Guido van Rossum0e548712002-08-09 16:14:33 +0000320
Guido van Rossume888cdc2002-08-17 14:50:24 +0000321def mktemp(suffix="", prefix=template, dir=None):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000322 """User-callable function to return a unique temporary file name. The
Guido van Rossum0e548712002-08-09 16:14:33 +0000323 file is not created.
324
Tim Peters04490bf2002-08-14 15:41:26 +0000325 Arguments are as for mkstemp, except that the 'text' argument is
Guido van Rossum0e548712002-08-09 16:14:33 +0000326 not accepted.
327
328 This function is unsafe and should not be used. The file name
329 refers to a file that did not exist at some point, but by the time
330 you get around to creating it, someone else may have beaten you to
331 the punch.
332 """
333
Guido van Rossum44f602d2002-11-22 15:56:29 +0000334## from warnings import warn as _warn
335## _warn("mktemp is a potential security risk to your program",
336## RuntimeWarning, stacklevel=2)
Guido van Rossum0e548712002-08-09 16:14:33 +0000337
Guido van Rossume888cdc2002-08-17 14:50:24 +0000338 if dir is None:
339 dir = gettempdir()
340
Guido van Rossum0e548712002-08-09 16:14:33 +0000341 names = _get_candidate_names()
Guido van Rossum805365e2007-05-07 22:24:25 +0000342 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000343 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000344 file = _os.path.join(dir, prefix + name + suffix)
Guido van Rossumb256159392003-11-10 02:16:36 +0000345 if not _exists(file):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000346 return file
Guido van Rossumca549821997-08-12 18:00:12 +0000347
Serhiy Storchaka7451a722013-02-09 22:25:49 +0200348 raise FileExistsError(_errno.EEXIST,
349 "No usable temporary filename found")
Guido van Rossumca549821997-08-12 18:00:12 +0000350
Christian Heimes3ecfea712008-02-09 20:51:34 +0000351
Guido van Rossum0e548712002-08-09 16:14:33 +0000352class _TemporaryFileWrapper:
Guido van Rossumca549821997-08-12 18:00:12 +0000353 """Temporary file wrapper
354
Guido van Rossum0e548712002-08-09 16:14:33 +0000355 This class provides a wrapper around files opened for
356 temporary use. In particular, it seeks to automatically
357 remove the file when it is no longer needed.
Guido van Rossumca549821997-08-12 18:00:12 +0000358 """
Tim Petersa255a722001-12-18 22:32:40 +0000359
Guido van Rossumd8faa362007-04-27 19:54:29 +0000360 def __init__(self, file, name, delete=True):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000361 self.file = file
Guido van Rossum0e548712002-08-09 16:14:33 +0000362 self.name = name
Tim Peters6ef966e2002-11-21 15:48:33 +0000363 self.close_called = False
Guido van Rossumd8faa362007-04-27 19:54:29 +0000364 self.delete = delete
Guido van Rossumca549821997-08-12 18:00:12 +0000365
Guido van Rossumca549821997-08-12 18:00:12 +0000366 def __getattr__(self, name):
Christian Heimes3ecfea712008-02-09 20:51:34 +0000367 # Attribute lookups are delegated to the underlying file
368 # and cached for non-numeric results
369 # (i.e. methods are cached, closed and friends are not)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000370 file = self.__dict__['file']
371 a = getattr(file, name)
Christian Heimes3ecfea712008-02-09 20:51:34 +0000372 if not isinstance(a, int):
Guido van Rossum6b708d51999-06-01 18:55:36 +0000373 setattr(self, name, a)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000374 return a
Guido van Rossumca549821997-08-12 18:00:12 +0000375
Christian Heimes3ecfea712008-02-09 20:51:34 +0000376 # The underlying __enter__ method returns the wrong object
377 # (self.file) so override it to return the wrapper
378 def __enter__(self):
379 self.file.__enter__()
380 return self
381
Christian Heimes36d1f8e2008-02-28 22:21:11 +0000382 # iter() doesn't use __getattr__ to find the __iter__ method
Christian Heimesc83b6292008-02-28 21:10:17 +0000383 def __iter__(self):
Christian Heimes36d1f8e2008-02-28 22:21:11 +0000384 return iter(self.file)
Christian Heimesc83b6292008-02-28 21:10:17 +0000385
Guido van Rossum0e548712002-08-09 16:14:33 +0000386 # NT provides delete-on-close as a primitive, so we don't need
387 # the wrapper to do anything special. We still use it so that
388 # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
389 if _os.name != 'nt':
Guido van Rossum0e548712002-08-09 16:14:33 +0000390 # Cache the unlinker so we don't get spurious errors at
391 # shutdown when the module-level "os" is None'd out. Note
392 # that this must be referenced as self.unlink, because the
393 # name TemporaryFileWrapper may also get None'd out before
394 # __del__ is called.
395 unlink = _os.unlink
Tim Peters1baa22a2001-01-12 10:02:46 +0000396
Guido van Rossum0e548712002-08-09 16:14:33 +0000397 def close(self):
398 if not self.close_called:
Tim Peters6ef966e2002-11-21 15:48:33 +0000399 self.close_called = True
Guido van Rossum0e548712002-08-09 16:14:33 +0000400 self.file.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000401 if self.delete:
402 self.unlink(self.name)
Tim Peters1baa22a2001-01-12 10:02:46 +0000403
Guido van Rossum0e548712002-08-09 16:14:33 +0000404 def __del__(self):
405 self.close()
Tim Peters1baa22a2001-01-12 10:02:46 +0000406
Christian Heimes3ecfea712008-02-09 20:51:34 +0000407 # Need to trap __exit__ as well to ensure the file gets
408 # deleted when used in a with statement
409 def __exit__(self, exc, value, tb):
410 result = self.file.__exit__(exc, value, tb)
411 self.close()
412 return result
Benjamin Peterson98d23f22009-06-30 22:27:25 +0000413 else:
414 def __exit__(self, exc, value, tb):
Benjamin Peterson3f5de132009-07-01 15:47:07 +0000415 self.file.__exit__(exc, value, tb)
Christian Heimes3ecfea712008-02-09 20:51:34 +0000416
417
Guido van Rossumf0c74162007-08-28 03:29:45 +0000418def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None,
419 newline=None, suffix="", prefix=template,
420 dir=None, delete=True):
Guido van Rossum0e548712002-08-09 16:14:33 +0000421 """Create and return a temporary file.
422 Arguments:
423 'prefix', 'suffix', 'dir' -- as for mkstemp.
Guido van Rossumf0c74162007-08-28 03:29:45 +0000424 'mode' -- the mode argument to io.open (default "w+b").
425 'buffering' -- the buffer size argument to io.open (default -1).
426 'encoding' -- the encoding argument to io.open (default None)
427 'newline' -- the newline argument to io.open (default None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000428 'delete' -- whether the file is deleted on close (default True).
Guido van Rossum0e548712002-08-09 16:14:33 +0000429 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000430
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000431 Returns an object with a file-like interface; the name of the file
432 is accessible as file.name. The file will be automatically deleted
Guido van Rossumd8faa362007-04-27 19:54:29 +0000433 when it is closed unless the 'delete' argument is set to False.
Guido van Rossum0e548712002-08-09 16:14:33 +0000434 """
Tim Peters1baa22a2001-01-12 10:02:46 +0000435
Guido van Rossume888cdc2002-08-17 14:50:24 +0000436 if dir is None:
437 dir = gettempdir()
438
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000439 flags = _bin_openflags
Tim Peters1baa22a2001-01-12 10:02:46 +0000440
Guido van Rossum0e548712002-08-09 16:14:33 +0000441 # Setting O_TEMPORARY in the flags causes the OS to delete
442 # the file when it is closed. This is only supported by Windows.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000443 if _os.name == 'nt' and delete:
Guido van Rossum0e548712002-08-09 16:14:33 +0000444 flags |= _os.O_TEMPORARY
Tim Peters1baa22a2001-01-12 10:02:46 +0000445
Guido van Rossum0e548712002-08-09 16:14:33 +0000446 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000447 file = _io.open(fd, mode, buffering=buffering,
448 newline=newline, encoding=encoding)
449
Guido van Rossumd8faa362007-04-27 19:54:29 +0000450 return _TemporaryFileWrapper(file, name, delete)
Guido van Rossum0e548712002-08-09 16:14:33 +0000451
Jason Tishler80c02af2002-08-14 15:10:09 +0000452if _os.name != 'posix' or _os.sys.platform == 'cygwin':
453 # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
454 # while it is open.
Guido van Rossum0e548712002-08-09 16:14:33 +0000455 TemporaryFile = NamedTemporaryFile
Tim Peters1baa22a2001-01-12 10:02:46 +0000456
457else:
Guido van Rossumf0c74162007-08-28 03:29:45 +0000458 def TemporaryFile(mode='w+b', buffering=-1, encoding=None,
459 newline=None, suffix="", prefix=template,
460 dir=None):
Guido van Rossum0e548712002-08-09 16:14:33 +0000461 """Create and return a temporary file.
462 Arguments:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000463 'prefix', 'suffix', 'dir' -- as for mkstemp.
Guido van Rossumf0c74162007-08-28 03:29:45 +0000464 'mode' -- the mode argument to io.open (default "w+b").
465 'buffering' -- the buffer size argument to io.open (default -1).
466 'encoding' -- the encoding argument to io.open (default None)
467 'newline' -- the newline argument to io.open (default None)
Guido van Rossum0e548712002-08-09 16:14:33 +0000468 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000469
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000470 Returns an object with a file-like interface. The file has no
471 name, and will cease to exist when it is closed.
Guido van Rossum0e548712002-08-09 16:14:33 +0000472 """
473
Guido van Rossume888cdc2002-08-17 14:50:24 +0000474 if dir is None:
475 dir = gettempdir()
476
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000477 flags = _bin_openflags
Guido van Rossum0e548712002-08-09 16:14:33 +0000478
479 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
480 try:
481 _os.unlink(name)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000482 return _io.open(fd, mode, buffering=buffering,
483 newline=newline, encoding=encoding)
Guido van Rossum0e548712002-08-09 16:14:33 +0000484 except:
485 _os.close(fd)
486 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +0000487
488class SpooledTemporaryFile:
Serhiy Storchaka4f169a72013-02-09 11:46:42 +0200489 """Temporary file wrapper, specialized to switch from BytesIO
490 or StringIO to a real file when it exceeds a certain size or
Guido van Rossumd8faa362007-04-27 19:54:29 +0000491 when a fileno is needed.
492 """
493 _rolled = False
494
Guido van Rossumf0c74162007-08-28 03:29:45 +0000495 def __init__(self, max_size=0, mode='w+b', buffering=-1,
496 encoding=None, newline=None,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000497 suffix="", prefix=template, dir=None):
Guido van Rossum9a634702007-07-09 10:24:45 +0000498 if 'b' in mode:
499 self._file = _io.BytesIO()
500 else:
Guido van Rossum5d212552007-10-29 16:42:51 +0000501 # Setting newline="\n" avoids newline translation;
502 # this is important because otherwise on Windows we'd
Guido van Rossum98297ee2007-11-06 21:34:58 +0000503 # hget double newline translation upon rollover().
Alexandre Vassalotti3ade6f92008-06-12 01:13:54 +0000504 self._file = _io.StringIO(newline="\n")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000505 self._max_size = max_size
506 self._rolled = False
Guido van Rossumf0c74162007-08-28 03:29:45 +0000507 self._TemporaryFileArgs = {'mode': mode, 'buffering': buffering,
508 'suffix': suffix, 'prefix': prefix,
509 'encoding': encoding, 'newline': newline,
510 'dir': dir}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000511
512 def _check(self, file):
513 if self._rolled: return
514 max_size = self._max_size
515 if max_size and file.tell() > max_size:
516 self.rollover()
517
518 def rollover(self):
519 if self._rolled: return
520 file = self._file
Guido van Rossumf0c74162007-08-28 03:29:45 +0000521 newfile = self._file = TemporaryFile(**self._TemporaryFileArgs)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000522 del self._TemporaryFileArgs
523
524 newfile.write(file.getvalue())
525 newfile.seek(file.tell(), 0)
526
527 self._rolled = True
528
Christian Heimes3ecfea712008-02-09 20:51:34 +0000529 # The method caching trick from NamedTemporaryFile
530 # won't work here, because _file may change from a
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300531 # BytesIO/StringIO instance to a real file. So we list
Christian Heimes3ecfea712008-02-09 20:51:34 +0000532 # all the methods directly.
533
534 # Context management protocol
535 def __enter__(self):
536 if self._file.closed:
537 raise ValueError("Cannot enter context with closed file")
538 return self
539
540 def __exit__(self, exc, value, tb):
541 self._file.close()
542
Guido van Rossumd8faa362007-04-27 19:54:29 +0000543 # file protocol
544 def __iter__(self):
545 return self._file.__iter__()
546
547 def close(self):
548 self._file.close()
549
550 @property
551 def closed(self):
552 return self._file.closed
553
554 @property
555 def encoding(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200556 try:
557 return self._file.encoding
558 except AttributeError:
559 if 'b' in self._TemporaryFileArgs['mode']:
560 raise
561 return self._TemporaryFileArgs['encoding']
Guido van Rossumd8faa362007-04-27 19:54:29 +0000562
563 def fileno(self):
564 self.rollover()
565 return self._file.fileno()
566
567 def flush(self):
568 self._file.flush()
569
570 def isatty(self):
571 return self._file.isatty()
572
573 @property
574 def mode(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200575 try:
576 return self._file.mode
577 except AttributeError:
578 return self._TemporaryFileArgs['mode']
Guido van Rossumd8faa362007-04-27 19:54:29 +0000579
580 @property
581 def name(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200582 try:
583 return self._file.name
584 except AttributeError:
585 return None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000586
587 @property
588 def newlines(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200589 try:
590 return self._file.newlines
591 except AttributeError:
592 if 'b' in self._TemporaryFileArgs['mode']:
593 raise
594 return self._TemporaryFileArgs['newline']
Guido van Rossumd8faa362007-04-27 19:54:29 +0000595
596 def read(self, *args):
597 return self._file.read(*args)
598
599 def readline(self, *args):
600 return self._file.readline(*args)
601
602 def readlines(self, *args):
603 return self._file.readlines(*args)
604
605 def seek(self, *args):
606 self._file.seek(*args)
607
608 @property
609 def softspace(self):
610 return self._file.softspace
611
612 def tell(self):
613 return self._file.tell()
614
Antoine Pitrou0e86a582011-11-25 18:03:09 +0100615 def truncate(self, size=None):
616 if size is None:
617 self._file.truncate()
618 else:
619 if size > self._max_size:
620 self.rollover()
621 self._file.truncate(size)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000622
623 def write(self, s):
624 file = self._file
625 rv = file.write(s)
626 self._check(file)
627 return rv
628
629 def writelines(self, iterable):
630 file = self._file
631 rv = file.writelines(iterable)
632 self._check(file)
633 return rv
634
Nick Coghlan543af752010-10-24 11:23:25 +0000635
636class TemporaryDirectory(object):
637 """Create and return a temporary directory. This has the same
638 behavior as mkdtemp but can be used as a context manager. For
639 example:
640
641 with TemporaryDirectory() as tmpdir:
642 ...
643
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300644 Upon exiting the context, the directory and everything contained
Nick Coghlan543af752010-10-24 11:23:25 +0000645 in it are removed.
646 """
647
648 def __init__(self, suffix="", prefix=template, dir=None):
Nick Coghlan543af752010-10-24 11:23:25 +0000649 self._closed = False
Andrew Svetlov737fb892012-12-18 21:14:22 +0200650 self.name = None # Handle mkdtemp raising an exception
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000651 self.name = mkdtemp(suffix, prefix, dir)
652
653 def __repr__(self):
654 return "<{} {!r}>".format(self.__class__.__name__, self.name)
Nick Coghlan543af752010-10-24 11:23:25 +0000655
656 def __enter__(self):
657 return self.name
658
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000659 def cleanup(self, _warn=False):
660 if self.name and not self._closed:
661 try:
662 self._rmtree(self.name)
663 except (TypeError, AttributeError) as ex:
664 # Issue #10188: Emit a warning on stderr
665 # if the directory could not be cleaned
666 # up due to missing globals
667 if "None" not in str(ex):
668 raise
669 print("ERROR: {!r} while cleaning up {!r}".format(ex, self,),
670 file=_sys.stderr)
671 return
Nick Coghlan543af752010-10-24 11:23:25 +0000672 self._closed = True
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000673 if _warn:
674 self._warn("Implicitly cleaning up {!r}".format(self),
675 ResourceWarning)
Nick Coghlan543af752010-10-24 11:23:25 +0000676
677 def __exit__(self, exc, value, tb):
678 self.cleanup()
679
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000680 def __del__(self):
681 # Issue a ResourceWarning if implicit cleanup needed
682 self.cleanup(_warn=True)
Nick Coghlan543af752010-10-24 11:23:25 +0000683
684 # XXX (ncoghlan): The following code attempts to make
685 # this class tolerant of the module nulling out process
686 # that happens during CPython interpreter shutdown
687 # Alas, it doesn't actually manage it. See issue #10188
688 _listdir = staticmethod(_os.listdir)
689 _path_join = staticmethod(_os.path.join)
690 _isdir = staticmethod(_os.path.isdir)
Charles-François Natalidef35432011-07-29 18:59:24 +0200691 _islink = staticmethod(_os.path.islink)
Nick Coghlan543af752010-10-24 11:23:25 +0000692 _remove = staticmethod(_os.remove)
693 _rmdir = staticmethod(_os.rmdir)
Florent Xicluna68f71a32011-10-28 16:06:23 +0200694 _os_error = OSError
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000695 _warn = _warnings.warn
Nick Coghlan543af752010-10-24 11:23:25 +0000696
697 def _rmtree(self, path):
698 # Essentially a stripped down version of shutil.rmtree. We can't
699 # use globals because they may be None'ed out at shutdown.
700 for name in self._listdir(path):
701 fullname = self._path_join(path, name)
702 try:
Charles-François Natalidef35432011-07-29 18:59:24 +0200703 isdir = self._isdir(fullname) and not self._islink(fullname)
Nick Coghlan543af752010-10-24 11:23:25 +0000704 except self._os_error:
705 isdir = False
706 if isdir:
707 self._rmtree(fullname)
708 else:
709 try:
710 self._remove(fullname)
711 except self._os_error:
712 pass
713 try:
714 self._rmdir(path)
715 except self._os_error:
716 pass