blob: b90e8269366c77d2053d54749d29a6f2a755b3ba [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.
13 template - the default prefix for all temporary names.
14 You may change this to control the default prefix.
15 tempdir - If this is set to a string before the first use of
16 any routine from this module, it will be considered as
17 another candidate location to store temporary files.
18"""
Skip Montanaro40fc1602001-03-01 04:27:19 +000019
Guido van Rossum0e548712002-08-09 16:14:33 +000020__all__ = [
21 "NamedTemporaryFile", "TemporaryFile", # high level safe interfaces
Nick Coghlan543af752010-10-24 11:23:25 +000022 "SpooledTemporaryFile", "TemporaryDirectory",
Guido van Rossum0e548712002-08-09 16:14:33 +000023 "mkstemp", "mkdtemp", # low level safe interfaces
24 "mktemp", # deprecated unsafe interface
25 "TMP_MAX", "gettempprefix", # constants
26 "tempdir", "gettempdir"
27 ]
Guido van Rossum41f95031992-03-31 19:02:01 +000028
Tim Peters4fd5a062002-01-28 23:11:23 +000029
Guido van Rossum0e548712002-08-09 16:14:33 +000030# Imports.
Tim Peters4fd5a062002-01-28 23:11:23 +000031
Nick Coghlan6b22f3f2010-12-12 15:24:21 +000032import warnings as _warnings
33import sys as _sys
Guido van Rossum9a634702007-07-09 10:24:45 +000034import io as _io
Guido van Rossum0e548712002-08-09 16:14:33 +000035import os as _os
36import errno as _errno
37from random import Random as _Random
38
Guido van Rossumd8faa362007-04-27 19:54:29 +000039try:
Guido van Rossum0e548712002-08-09 16:14:33 +000040 import fcntl as _fcntl
Tim Peters90ee7eb2004-07-18 23:58:17 +000041except ImportError:
Tim Peters291f14e2003-07-22 02:50:01 +000042 def _set_cloexec(fd):
43 pass
44else:
Guido van Rossum0e548712002-08-09 16:14:33 +000045 def _set_cloexec(fd):
Tim Peters90ee7eb2004-07-18 23:58:17 +000046 try:
47 flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0)
48 except IOError:
49 pass
Alex Martellif09994e2003-11-09 16:44:09 +000050 else:
Guido van Rossum0e548712002-08-09 16:14:33 +000051 # flags read successfully, modify
52 flags |= _fcntl.FD_CLOEXEC
53 _fcntl.fcntl(fd, _fcntl.F_SETFD, flags)
Tim Peters291f14e2003-07-22 02:50:01 +000054
Guido van Rossum0e548712002-08-09 16:14:33 +000055
56try:
Georg Brandl2067bfd2008-05-25 13:05:15 +000057 import _thread
Guido van Rossuma0934242002-12-30 22:36:09 +000058except ImportError:
Georg Brandl2067bfd2008-05-25 13:05:15 +000059 import _dummy_thread as _thread
Guido van Rossuma0934242002-12-30 22:36:09 +000060_allocate_lock = _thread.allocate_lock
Guido van Rossum0e548712002-08-09 16:14:33 +000061
62_text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL
Tim Petersa0d55de2002-08-09 18:01:01 +000063if hasattr(_os, 'O_NOINHERIT'):
64 _text_openflags |= _os.O_NOINHERIT
65if hasattr(_os, 'O_NOFOLLOW'):
66 _text_openflags |= _os.O_NOFOLLOW
Guido van Rossum0e548712002-08-09 16:14:33 +000067
68_bin_openflags = _text_openflags
Tim Petersa0d55de2002-08-09 18:01:01 +000069if hasattr(_os, 'O_BINARY'):
70 _bin_openflags |= _os.O_BINARY
Guido van Rossum0e548712002-08-09 16:14:33 +000071
72if hasattr(_os, 'TMP_MAX'):
73 TMP_MAX = _os.TMP_MAX
74else:
75 TMP_MAX = 10000
76
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:
88 # Fallback. All we need is something that raises os.error if the
89 # file doesn't exist.
90 def _stat(fn):
91 try:
92 f = open(fn)
93 except IOError:
94 raise _os.error
95 f.close()
96
97def _exists(fn):
98 try:
99 _stat(fn)
100 except _os.error:
101 return False
102 else:
103 return True
104
Guido van Rossum0e548712002-08-09 16:14:33 +0000105class _RandomNameSequence:
106 """An instance of _RandomNameSequence generates an endless
107 sequence of unpredictable strings which can safely be incorporated
108 into file names. Each string is six characters long. Multiple
109 threads can safely use the same instance at the same time.
110
111 _RandomNameSequence is an iterator."""
112
Raymond Hettinger572895b2010-11-09 03:43:58 +0000113 characters = "abcdefghijklmnopqrstuvwxyz0123456789_"
Guido van Rossum0e548712002-08-09 16:14:33 +0000114
Antoine Pitrou4558bad2011-11-25 21:28:15 +0100115 @property
116 def rng(self):
117 cur_pid = _os.getpid()
118 if cur_pid != getattr(self, '_rng_pid', None):
119 self._rng = _Random()
120 self._rng_pid = cur_pid
121 return self._rng
Tim Peters97701b52002-11-21 15:59:59 +0000122
Guido van Rossum0e548712002-08-09 16:14:33 +0000123 def __iter__(self):
124 return self
125
Georg Brandla18af4e2007-04-21 15:47:16 +0000126 def __next__(self):
Guido van Rossum0e548712002-08-09 16:14:33 +0000127 c = self.characters
Tim Peters97701b52002-11-21 15:59:59 +0000128 choose = self.rng.choice
Raymond Hettinger572895b2010-11-09 03:43:58 +0000129 letters = [choose(c) for dummy in "123456"]
130 return ''.join(letters)
Guido van Rossum0e548712002-08-09 16:14:33 +0000131
132def _candidate_tempdir_list():
133 """Generate a list of candidate temporary directories which
134 _get_default_tempdir will try."""
135
136 dirlist = []
137
138 # First, try the environment.
139 for envname in 'TMPDIR', 'TEMP', 'TMP':
140 dirname = _os.getenv(envname)
141 if dirname: dirlist.append(dirname)
142
143 # Failing that, try OS-specific locations.
Alexandre Vassalottieca20b62008-05-16 02:54:33 +0000144 if _os.name == 'nt':
Guido van Rossum0e548712002-08-09 16:14:33 +0000145 dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
146 else:
147 dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
148
149 # As a last resort, the current directory.
150 try:
151 dirlist.append(_os.getcwd())
152 except (AttributeError, _os.error):
153 dirlist.append(_os.curdir)
154
155 return dirlist
Tim Petersa0d55de2002-08-09 18:01:01 +0000156
Guido van Rossum0e548712002-08-09 16:14:33 +0000157def _get_default_tempdir():
158 """Calculate the default directory to use for temporary files.
Guido van Rossume888cdc2002-08-17 14:50:24 +0000159 This routine should be called exactly once.
Guido van Rossum0e548712002-08-09 16:14:33 +0000160
161 We determine whether or not a candidate temp dir is usable by
162 trying to create and write to a file in that directory. If this
163 is successful, the test file is deleted. To prevent denial of
164 service, the name of the test file must be randomized."""
165
166 namer = _RandomNameSequence()
167 dirlist = _candidate_tempdir_list()
Guido van Rossum0e548712002-08-09 16:14:33 +0000168
169 for dir in dirlist:
170 if dir != _os.curdir:
171 dir = _os.path.normcase(_os.path.abspath(dir))
172 # Try only a few names per directory.
Guido van Rossum805365e2007-05-07 22:24:25 +0000173 for seq in range(100):
Georg Brandla18af4e2007-04-21 15:47:16 +0000174 name = next(namer)
Guido van Rossum0e548712002-08-09 16:14:33 +0000175 filename = _os.path.join(dir, name)
176 try:
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000177 fd = _os.open(filename, _bin_openflags, 0o600)
Serhiy Storchakaf6b361e2013-02-13 00:35:30 +0200178 try:
179 try:
Serhiy Storchaka76a2ed12013-02-13 00:59:26 +0200180 with _io.open(fd, 'wb', closefd=False) as fp:
181 fp.write(b'blat')
Serhiy Storchakaf6b361e2013-02-13 00:35:30 +0200182 finally:
183 _os.close(fd)
184 finally:
185 _os.unlink(filename)
Guido van Rossum0e548712002-08-09 16:14:33 +0000186 return dir
Guido van Rossumb940e112007-01-10 16:19:56 +0000187 except (OSError, IOError) as e:
Georg Brandl7816e512007-10-22 12:42:46 +0000188 if e.args[0] != _errno.EEXIST:
Guido van Rossum0e548712002-08-09 16:14:33 +0000189 break # no point trying more names in this directory
190 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000191 raise IOError(_errno.ENOENT,
192 "No usable temporary directory found in %s" % dirlist)
Guido van Rossum0e548712002-08-09 16:14:33 +0000193
Guido van Rossume888cdc2002-08-17 14:50:24 +0000194_name_sequence = None
195
Guido van Rossum0e548712002-08-09 16:14:33 +0000196def _get_candidate_names():
197 """Common setup sequence for all user-callable interfaces."""
198
Guido van Rossume888cdc2002-08-17 14:50:24 +0000199 global _name_sequence
200 if _name_sequence is None:
201 _once_lock.acquire()
202 try:
203 if _name_sequence is None:
204 _name_sequence = _RandomNameSequence()
205 finally:
206 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000207 return _name_sequence
Guido van Rossum41f95031992-03-31 19:02:01 +0000208
209
Guido van Rossum0e548712002-08-09 16:14:33 +0000210def _mkstemp_inner(dir, pre, suf, flags):
211 """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
Tim Peters9fadfb02001-01-13 03:04:02 +0000212
Guido van Rossum0e548712002-08-09 16:14:33 +0000213 names = _get_candidate_names()
214
Guido van Rossum805365e2007-05-07 22:24:25 +0000215 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000216 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000217 file = _os.path.join(dir, pre + name + suf)
218 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000219 fd = _os.open(file, flags, 0o600)
Guido van Rossum0e548712002-08-09 16:14:33 +0000220 _set_cloexec(fd)
Martin v. Löwisd6625482003-10-12 17:37:01 +0000221 return (fd, _os.path.abspath(file))
Guido van Rossumb940e112007-01-10 16:19:56 +0000222 except OSError as e:
Guido van Rossum0e548712002-08-09 16:14:33 +0000223 if e.errno == _errno.EEXIST:
224 continue # try again
225 raise
226
Collin Winterce36ad82007-08-30 01:19:48 +0000227 raise IOError(_errno.EEXIST, "No usable temporary file name found")
Tim Petersa0d55de2002-08-09 18:01:01 +0000228
Guido van Rossum0e548712002-08-09 16:14:33 +0000229
230# User visible interfaces.
Guido van Rossumb0e57181998-10-14 20:27:05 +0000231
Guido van Rossum41f95031992-03-31 19:02:01 +0000232def gettempprefix():
Guido van Rossum0e548712002-08-09 16:14:33 +0000233 """Accessor for tempdir.template."""
234 return template
Tim Peters9fadfb02001-01-13 03:04:02 +0000235
Guido van Rossume888cdc2002-08-17 14:50:24 +0000236tempdir = None
237
Guido van Rossum0e548712002-08-09 16:14:33 +0000238def gettempdir():
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000239 """Accessor for tempfile.tempdir."""
Guido van Rossume888cdc2002-08-17 14:50:24 +0000240 global tempdir
241 if tempdir is None:
242 _once_lock.acquire()
243 try:
244 if tempdir is None:
245 tempdir = _get_default_tempdir()
246 finally:
247 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000248 return tempdir
249
Guido van Rossume888cdc2002-08-17 14:50:24 +0000250def mkstemp(suffix="", prefix=template, dir=None, text=False):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000251 """User-callable function to create and return a unique temporary
Guido van Rossum0e548712002-08-09 16:14:33 +0000252 file. The return value is a pair (fd, name) where fd is the
253 file descriptor returned by os.open, and name is the filename.
254
255 If 'suffix' is specified, the file name will end with that suffix,
256 otherwise there will be no suffix.
257
258 If 'prefix' is specified, the file name will begin with that prefix,
259 otherwise a default prefix is used.
260
261 If 'dir' is specified, the file will be created in that directory,
262 otherwise a default directory is used.
263
Tim Peters04490bf2002-08-14 15:41:26 +0000264 If 'text' is specified and true, the file is opened in text
265 mode. Else (the default) the file is opened in binary mode. On
266 some operating systems, this makes no difference.
Guido van Rossum0e548712002-08-09 16:14:33 +0000267
268 The file is readable and writable only by the creating user ID.
269 If the operating system uses permission bits to indicate whether a
270 file is executable, the file is executable by no one. The file
271 descriptor is not inherited by children of this process.
272
273 Caller is responsible for deleting the file when done with it.
Tim Peters9fadfb02001-01-13 03:04:02 +0000274 """
275
Guido van Rossume888cdc2002-08-17 14:50:24 +0000276 if dir is None:
277 dir = gettempdir()
278
Tim Peters04490bf2002-08-14 15:41:26 +0000279 if text:
Guido van Rossum0e548712002-08-09 16:14:33 +0000280 flags = _text_openflags
Tim Peters04490bf2002-08-14 15:41:26 +0000281 else:
282 flags = _bin_openflags
Guido van Rossum0e548712002-08-09 16:14:33 +0000283
284 return _mkstemp_inner(dir, prefix, suffix, flags)
Guido van Rossumcff34541992-01-14 18:31:56 +0000285
Guido van Rossumeee94981991-11-12 15:38:08 +0000286
Guido van Rossume888cdc2002-08-17 14:50:24 +0000287def mkdtemp(suffix="", prefix=template, dir=None):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000288 """User-callable function to create and return a unique temporary
Guido van Rossum0e548712002-08-09 16:14:33 +0000289 directory. The return value is the pathname of the directory.
290
Tim Peters04490bf2002-08-14 15:41:26 +0000291 Arguments are as for mkstemp, except that the 'text' argument is
Guido van Rossum0e548712002-08-09 16:14:33 +0000292 not accepted.
293
294 The directory is readable, writable, and searchable only by the
295 creating user.
296
297 Caller is responsible for deleting the directory when done with it.
298 """
299
Guido van Rossume888cdc2002-08-17 14:50:24 +0000300 if dir is None:
301 dir = gettempdir()
302
Guido van Rossum0e548712002-08-09 16:14:33 +0000303 names = _get_candidate_names()
Tim Petersa0d55de2002-08-09 18:01:01 +0000304
Guido van Rossum805365e2007-05-07 22:24:25 +0000305 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000306 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000307 file = _os.path.join(dir, prefix + name + suffix)
308 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000309 _os.mkdir(file, 0o700)
Guido van Rossum0e548712002-08-09 16:14:33 +0000310 return file
Guido van Rossumb940e112007-01-10 16:19:56 +0000311 except OSError as e:
Guido van Rossum0e548712002-08-09 16:14:33 +0000312 if e.errno == _errno.EEXIST:
313 continue # try again
314 raise
315
Collin Winterce36ad82007-08-30 01:19:48 +0000316 raise IOError(_errno.EEXIST, "No usable temporary directory name found")
Guido van Rossum0e548712002-08-09 16:14:33 +0000317
Guido van Rossume888cdc2002-08-17 14:50:24 +0000318def mktemp(suffix="", prefix=template, dir=None):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000319 """User-callable function to return a unique temporary file name. The
Guido van Rossum0e548712002-08-09 16:14:33 +0000320 file is not created.
321
Tim Peters04490bf2002-08-14 15:41:26 +0000322 Arguments are as for mkstemp, except that the 'text' argument is
Guido van Rossum0e548712002-08-09 16:14:33 +0000323 not accepted.
324
325 This function is unsafe and should not be used. The file name
326 refers to a file that did not exist at some point, but by the time
327 you get around to creating it, someone else may have beaten you to
328 the punch.
329 """
330
Guido van Rossum44f602d2002-11-22 15:56:29 +0000331## from warnings import warn as _warn
332## _warn("mktemp is a potential security risk to your program",
333## RuntimeWarning, stacklevel=2)
Guido van Rossum0e548712002-08-09 16:14:33 +0000334
Guido van Rossume888cdc2002-08-17 14:50:24 +0000335 if dir is None:
336 dir = gettempdir()
337
Guido van Rossum0e548712002-08-09 16:14:33 +0000338 names = _get_candidate_names()
Guido van Rossum805365e2007-05-07 22:24:25 +0000339 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000340 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000341 file = _os.path.join(dir, prefix + name + suffix)
Guido van Rossumb256159392003-11-10 02:16:36 +0000342 if not _exists(file):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000343 return file
Guido van Rossumca549821997-08-12 18:00:12 +0000344
Collin Winterce36ad82007-08-30 01:19:48 +0000345 raise IOError(_errno.EEXIST, "No usable temporary filename found")
Guido van Rossumca549821997-08-12 18:00:12 +0000346
Christian Heimes3ecfea712008-02-09 20:51:34 +0000347
Guido van Rossum0e548712002-08-09 16:14:33 +0000348class _TemporaryFileWrapper:
Guido van Rossumca549821997-08-12 18:00:12 +0000349 """Temporary file wrapper
350
Guido van Rossum0e548712002-08-09 16:14:33 +0000351 This class provides a wrapper around files opened for
352 temporary use. In particular, it seeks to automatically
353 remove the file when it is no longer needed.
Guido van Rossumca549821997-08-12 18:00:12 +0000354 """
Tim Petersa255a722001-12-18 22:32:40 +0000355
Guido van Rossumd8faa362007-04-27 19:54:29 +0000356 def __init__(self, file, name, delete=True):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000357 self.file = file
Guido van Rossum0e548712002-08-09 16:14:33 +0000358 self.name = name
Tim Peters6ef966e2002-11-21 15:48:33 +0000359 self.close_called = False
Guido van Rossumd8faa362007-04-27 19:54:29 +0000360 self.delete = delete
Guido van Rossumca549821997-08-12 18:00:12 +0000361
Guido van Rossumca549821997-08-12 18:00:12 +0000362 def __getattr__(self, name):
Christian Heimes3ecfea712008-02-09 20:51:34 +0000363 # Attribute lookups are delegated to the underlying file
364 # and cached for non-numeric results
365 # (i.e. methods are cached, closed and friends are not)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000366 file = self.__dict__['file']
367 a = getattr(file, name)
Christian Heimes3ecfea712008-02-09 20:51:34 +0000368 if not isinstance(a, int):
Guido van Rossum6b708d51999-06-01 18:55:36 +0000369 setattr(self, name, a)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000370 return a
Guido van Rossumca549821997-08-12 18:00:12 +0000371
Christian Heimes3ecfea712008-02-09 20:51:34 +0000372 # The underlying __enter__ method returns the wrong object
373 # (self.file) so override it to return the wrapper
374 def __enter__(self):
375 self.file.__enter__()
376 return self
377
Christian Heimes36d1f8e2008-02-28 22:21:11 +0000378 # iter() doesn't use __getattr__ to find the __iter__ method
Christian Heimesc83b6292008-02-28 21:10:17 +0000379 def __iter__(self):
Christian Heimes36d1f8e2008-02-28 22:21:11 +0000380 return iter(self.file)
Christian Heimesc83b6292008-02-28 21:10:17 +0000381
Guido van Rossum0e548712002-08-09 16:14:33 +0000382 # NT provides delete-on-close as a primitive, so we don't need
383 # the wrapper to do anything special. We still use it so that
384 # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
385 if _os.name != 'nt':
Guido van Rossum0e548712002-08-09 16:14:33 +0000386 # Cache the unlinker so we don't get spurious errors at
387 # shutdown when the module-level "os" is None'd out. Note
388 # that this must be referenced as self.unlink, because the
389 # name TemporaryFileWrapper may also get None'd out before
390 # __del__ is called.
391 unlink = _os.unlink
Tim Peters1baa22af2001-01-12 10:02:46 +0000392
Guido van Rossum0e548712002-08-09 16:14:33 +0000393 def close(self):
394 if not self.close_called:
Tim Peters6ef966e2002-11-21 15:48:33 +0000395 self.close_called = True
Guido van Rossum0e548712002-08-09 16:14:33 +0000396 self.file.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000397 if self.delete:
398 self.unlink(self.name)
Tim Peters1baa22af2001-01-12 10:02:46 +0000399
Guido van Rossum0e548712002-08-09 16:14:33 +0000400 def __del__(self):
401 self.close()
Tim Peters1baa22af2001-01-12 10:02:46 +0000402
Christian Heimes3ecfea712008-02-09 20:51:34 +0000403 # Need to trap __exit__ as well to ensure the file gets
404 # deleted when used in a with statement
405 def __exit__(self, exc, value, tb):
406 result = self.file.__exit__(exc, value, tb)
407 self.close()
408 return result
Benjamin Peterson98d23f22009-06-30 22:27:25 +0000409 else:
410 def __exit__(self, exc, value, tb):
Benjamin Peterson3f5de132009-07-01 15:47:07 +0000411 self.file.__exit__(exc, value, tb)
Christian Heimes3ecfea712008-02-09 20:51:34 +0000412
413
Guido van Rossumf0c74162007-08-28 03:29:45 +0000414def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None,
415 newline=None, suffix="", prefix=template,
416 dir=None, delete=True):
Guido van Rossum0e548712002-08-09 16:14:33 +0000417 """Create and return a temporary file.
418 Arguments:
419 'prefix', 'suffix', 'dir' -- as for mkstemp.
Guido van Rossumf0c74162007-08-28 03:29:45 +0000420 'mode' -- the mode argument to io.open (default "w+b").
421 'buffering' -- the buffer size argument to io.open (default -1).
422 'encoding' -- the encoding argument to io.open (default None)
423 'newline' -- the newline argument to io.open (default None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000424 'delete' -- whether the file is deleted on close (default True).
Guido van Rossum0e548712002-08-09 16:14:33 +0000425 The file is created as mkstemp() would do it.
Tim Peters1baa22af2001-01-12 10:02:46 +0000426
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000427 Returns an object with a file-like interface; the name of the file
428 is accessible as file.name. The file will be automatically deleted
Guido van Rossumd8faa362007-04-27 19:54:29 +0000429 when it is closed unless the 'delete' argument is set to False.
Guido van Rossum0e548712002-08-09 16:14:33 +0000430 """
Tim Peters1baa22af2001-01-12 10:02:46 +0000431
Guido van Rossume888cdc2002-08-17 14:50:24 +0000432 if dir is None:
433 dir = gettempdir()
434
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000435 flags = _bin_openflags
Tim Peters1baa22af2001-01-12 10:02:46 +0000436
Guido van Rossum0e548712002-08-09 16:14:33 +0000437 # Setting O_TEMPORARY in the flags causes the OS to delete
438 # the file when it is closed. This is only supported by Windows.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000439 if _os.name == 'nt' and delete:
Guido van Rossum0e548712002-08-09 16:14:33 +0000440 flags |= _os.O_TEMPORARY
Tim Peters1baa22af2001-01-12 10:02:46 +0000441
Guido van Rossum0e548712002-08-09 16:14:33 +0000442 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000443 file = _io.open(fd, mode, buffering=buffering,
444 newline=newline, encoding=encoding)
445
Guido van Rossumd8faa362007-04-27 19:54:29 +0000446 return _TemporaryFileWrapper(file, name, delete)
Guido van Rossum0e548712002-08-09 16:14:33 +0000447
Jason Tishler80c02af2002-08-14 15:10:09 +0000448if _os.name != 'posix' or _os.sys.platform == 'cygwin':
449 # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
450 # while it is open.
Guido van Rossum0e548712002-08-09 16:14:33 +0000451 TemporaryFile = NamedTemporaryFile
Tim Peters1baa22af2001-01-12 10:02:46 +0000452
453else:
Guido van Rossumf0c74162007-08-28 03:29:45 +0000454 def TemporaryFile(mode='w+b', buffering=-1, encoding=None,
455 newline=None, suffix="", prefix=template,
456 dir=None):
Guido van Rossum0e548712002-08-09 16:14:33 +0000457 """Create and return a temporary file.
458 Arguments:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000459 'prefix', 'suffix', 'dir' -- as for mkstemp.
Guido van Rossumf0c74162007-08-28 03:29:45 +0000460 'mode' -- the mode argument to io.open (default "w+b").
461 'buffering' -- the buffer size argument to io.open (default -1).
462 'encoding' -- the encoding argument to io.open (default None)
463 'newline' -- the newline argument to io.open (default None)
Guido van Rossum0e548712002-08-09 16:14:33 +0000464 The file is created as mkstemp() would do it.
Tim Peters1baa22af2001-01-12 10:02:46 +0000465
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000466 Returns an object with a file-like interface. The file has no
467 name, and will cease to exist when it is closed.
Guido van Rossum0e548712002-08-09 16:14:33 +0000468 """
469
Guido van Rossume888cdc2002-08-17 14:50:24 +0000470 if dir is None:
471 dir = gettempdir()
472
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000473 flags = _bin_openflags
Guido van Rossum0e548712002-08-09 16:14:33 +0000474
475 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
476 try:
477 _os.unlink(name)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000478 return _io.open(fd, mode, buffering=buffering,
479 newline=newline, encoding=encoding)
Guido van Rossum0e548712002-08-09 16:14:33 +0000480 except:
481 _os.close(fd)
482 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +0000483
484class SpooledTemporaryFile:
Serhiy Storchaka4f169a72013-02-09 11:46:42 +0200485 """Temporary file wrapper, specialized to switch from BytesIO
486 or StringIO to a real file when it exceeds a certain size or
Guido van Rossumd8faa362007-04-27 19:54:29 +0000487 when a fileno is needed.
488 """
489 _rolled = False
490
Guido van Rossumf0c74162007-08-28 03:29:45 +0000491 def __init__(self, max_size=0, mode='w+b', buffering=-1,
492 encoding=None, newline=None,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000493 suffix="", prefix=template, dir=None):
Guido van Rossum9a634702007-07-09 10:24:45 +0000494 if 'b' in mode:
495 self._file = _io.BytesIO()
496 else:
Guido van Rossum5d212552007-10-29 16:42:51 +0000497 # Setting newline="\n" avoids newline translation;
498 # this is important because otherwise on Windows we'd
Guido van Rossum98297ee2007-11-06 21:34:58 +0000499 # hget double newline translation upon rollover().
Alexandre Vassalotti3ade6f92008-06-12 01:13:54 +0000500 self._file = _io.StringIO(newline="\n")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000501 self._max_size = max_size
502 self._rolled = False
Guido van Rossumf0c74162007-08-28 03:29:45 +0000503 self._TemporaryFileArgs = {'mode': mode, 'buffering': buffering,
504 'suffix': suffix, 'prefix': prefix,
505 'encoding': encoding, 'newline': newline,
506 'dir': dir}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000507
508 def _check(self, file):
509 if self._rolled: return
510 max_size = self._max_size
511 if max_size and file.tell() > max_size:
512 self.rollover()
513
514 def rollover(self):
515 if self._rolled: return
516 file = self._file
Guido van Rossumf0c74162007-08-28 03:29:45 +0000517 newfile = self._file = TemporaryFile(**self._TemporaryFileArgs)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000518 del self._TemporaryFileArgs
519
520 newfile.write(file.getvalue())
521 newfile.seek(file.tell(), 0)
522
523 self._rolled = True
524
Christian Heimes3ecfea712008-02-09 20:51:34 +0000525 # The method caching trick from NamedTemporaryFile
526 # won't work here, because _file may change from a
527 # _StringIO instance to a real file. So we list
528 # all the methods directly.
529
530 # Context management protocol
531 def __enter__(self):
532 if self._file.closed:
533 raise ValueError("Cannot enter context with closed file")
534 return self
535
536 def __exit__(self, exc, value, tb):
537 self._file.close()
538
Guido van Rossumd8faa362007-04-27 19:54:29 +0000539 # file protocol
540 def __iter__(self):
541 return self._file.__iter__()
542
543 def close(self):
544 self._file.close()
545
546 @property
547 def closed(self):
548 return self._file.closed
549
550 @property
551 def encoding(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200552 try:
553 return self._file.encoding
554 except AttributeError:
555 if 'b' in self._TemporaryFileArgs['mode']:
556 raise
557 return self._TemporaryFileArgs['encoding']
Guido van Rossumd8faa362007-04-27 19:54:29 +0000558
559 def fileno(self):
560 self.rollover()
561 return self._file.fileno()
562
563 def flush(self):
564 self._file.flush()
565
566 def isatty(self):
567 return self._file.isatty()
568
569 @property
570 def mode(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200571 try:
572 return self._file.mode
573 except AttributeError:
574 return self._TemporaryFileArgs['mode']
Guido van Rossumd8faa362007-04-27 19:54:29 +0000575
576 @property
577 def name(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200578 try:
579 return self._file.name
580 except AttributeError:
581 return None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000582
583 @property
584 def newlines(self):
Serhiy Storchakabbbbe8e2013-02-09 12:21:14 +0200585 try:
586 return self._file.newlines
587 except AttributeError:
588 if 'b' in self._TemporaryFileArgs['mode']:
589 raise
590 return self._TemporaryFileArgs['newline']
Guido van Rossumd8faa362007-04-27 19:54:29 +0000591
592 def read(self, *args):
593 return self._file.read(*args)
594
595 def readline(self, *args):
596 return self._file.readline(*args)
597
598 def readlines(self, *args):
599 return self._file.readlines(*args)
600
601 def seek(self, *args):
602 self._file.seek(*args)
603
604 @property
605 def softspace(self):
606 return self._file.softspace
607
608 def tell(self):
609 return self._file.tell()
610
611 def truncate(self):
612 self._file.truncate()
613
614 def write(self, s):
615 file = self._file
616 rv = file.write(s)
617 self._check(file)
618 return rv
619
620 def writelines(self, iterable):
621 file = self._file
622 rv = file.writelines(iterable)
623 self._check(file)
624 return rv
625
Nick Coghlan543af752010-10-24 11:23:25 +0000626
627class TemporaryDirectory(object):
628 """Create and return a temporary directory. This has the same
629 behavior as mkdtemp but can be used as a context manager. For
630 example:
631
632 with TemporaryDirectory() as tmpdir:
633 ...
634
635 Upon exiting the context, the directory and everthing contained
636 in it are removed.
637 """
638
639 def __init__(self, suffix="", prefix=template, dir=None):
Nick Coghlan543af752010-10-24 11:23:25 +0000640 self._closed = False
Andrew Svetlov737fb892012-12-18 21:14:22 +0200641 self.name = None # Handle mkdtemp raising an exception
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000642 self.name = mkdtemp(suffix, prefix, dir)
643
644 def __repr__(self):
645 return "<{} {!r}>".format(self.__class__.__name__, self.name)
Nick Coghlan543af752010-10-24 11:23:25 +0000646
647 def __enter__(self):
648 return self.name
649
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000650 def cleanup(self, _warn=False):
651 if self.name and not self._closed:
652 try:
653 self._rmtree(self.name)
654 except (TypeError, AttributeError) as ex:
655 # Issue #10188: Emit a warning on stderr
656 # if the directory could not be cleaned
657 # up due to missing globals
658 if "None" not in str(ex):
659 raise
660 print("ERROR: {!r} while cleaning up {!r}".format(ex, self,),
661 file=_sys.stderr)
662 return
Nick Coghlan543af752010-10-24 11:23:25 +0000663 self._closed = True
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000664 if _warn:
665 self._warn("Implicitly cleaning up {!r}".format(self),
666 ResourceWarning)
Nick Coghlan543af752010-10-24 11:23:25 +0000667
668 def __exit__(self, exc, value, tb):
669 self.cleanup()
670
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000671 def __del__(self):
672 # Issue a ResourceWarning if implicit cleanup needed
673 self.cleanup(_warn=True)
Nick Coghlan543af752010-10-24 11:23:25 +0000674
675 # XXX (ncoghlan): The following code attempts to make
676 # this class tolerant of the module nulling out process
677 # that happens during CPython interpreter shutdown
678 # Alas, it doesn't actually manage it. See issue #10188
679 _listdir = staticmethod(_os.listdir)
680 _path_join = staticmethod(_os.path.join)
681 _isdir = staticmethod(_os.path.isdir)
Charles-François Natalidef35432011-07-29 18:59:24 +0200682 _islink = staticmethod(_os.path.islink)
Nick Coghlan543af752010-10-24 11:23:25 +0000683 _remove = staticmethod(_os.remove)
684 _rmdir = staticmethod(_os.rmdir)
685 _os_error = _os.error
Nick Coghlan6b22f3f2010-12-12 15:24:21 +0000686 _warn = _warnings.warn
Nick Coghlan543af752010-10-24 11:23:25 +0000687
688 def _rmtree(self, path):
689 # Essentially a stripped down version of shutil.rmtree. We can't
690 # use globals because they may be None'ed out at shutdown.
691 for name in self._listdir(path):
692 fullname = self._path_join(path, name)
693 try:
Charles-François Natalidef35432011-07-29 18:59:24 +0200694 isdir = self._isdir(fullname) and not self._islink(fullname)
Nick Coghlan543af752010-10-24 11:23:25 +0000695 except self._os_error:
696 isdir = False
697 if isdir:
698 self._rmtree(fullname)
699 else:
700 try:
701 self._remove(fullname)
702 except self._os_error:
703 pass
704 try:
705 self._rmdir(path)
706 except self._os_error:
707 pass