blob: 7e0378443e011beb6aeb4ba443e0be467ac5e150 [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
Guido van Rossum9a634702007-07-09 10:24:45 +000032import io as _io
Guido van Rossum0e548712002-08-09 16:14:33 +000033import os as _os
34import errno as _errno
35from 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)
46 except IOError:
47 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
Tim Petersbd7b4c72002-08-13 23:33:56 +000075template = "tmp"
Guido van Rossum0e548712002-08-09 16:14:33 +000076
Guido van Rossum0e548712002-08-09 16:14:33 +000077# Internal routines.
78
79_once_lock = _allocate_lock()
80
Guido van Rossumb256159392003-11-10 02:16:36 +000081if hasattr(_os, "lstat"):
82 _stat = _os.lstat
83elif hasattr(_os, "stat"):
84 _stat = _os.stat
85else:
86 # Fallback. All we need is something that raises os.error if the
87 # file doesn't exist.
88 def _stat(fn):
89 try:
90 f = open(fn)
91 except IOError:
92 raise _os.error
93 f.close()
94
95def _exists(fn):
96 try:
97 _stat(fn)
98 except _os.error:
99 return False
100 else:
101 return True
102
Guido van Rossum0e548712002-08-09 16:14:33 +0000103class _RandomNameSequence:
104 """An instance of _RandomNameSequence generates an endless
105 sequence of unpredictable strings which can safely be incorporated
106 into file names. Each string is six characters long. Multiple
107 threads can safely use the same instance at the same time.
108
109 _RandomNameSequence is an iterator."""
110
Raymond Hettinger572895b2010-11-09 03:43:58 +0000111 characters = "abcdefghijklmnopqrstuvwxyz0123456789_"
Guido van Rossum0e548712002-08-09 16:14:33 +0000112
113 def __init__(self):
Guido van Rossum0e548712002-08-09 16:14:33 +0000114 self.rng = _Random()
Tim Peters97701b52002-11-21 15:59:59 +0000115
Guido van Rossum0e548712002-08-09 16:14:33 +0000116 def __iter__(self):
117 return self
118
Georg Brandla18af4e2007-04-21 15:47:16 +0000119 def __next__(self):
Guido van Rossum0e548712002-08-09 16:14:33 +0000120 c = self.characters
Tim Peters97701b52002-11-21 15:59:59 +0000121 choose = self.rng.choice
Raymond Hettinger572895b2010-11-09 03:43:58 +0000122 letters = [choose(c) for dummy in "123456"]
123 return ''.join(letters)
Guido van Rossum0e548712002-08-09 16:14:33 +0000124
125def _candidate_tempdir_list():
126 """Generate a list of candidate temporary directories which
127 _get_default_tempdir will try."""
128
129 dirlist = []
130
131 # First, try the environment.
132 for envname in 'TMPDIR', 'TEMP', 'TMP':
133 dirname = _os.getenv(envname)
134 if dirname: dirlist.append(dirname)
135
136 # Failing that, try OS-specific locations.
Alexandre Vassalottieca20b62008-05-16 02:54:33 +0000137 if _os.name == 'nt':
Guido van Rossum0e548712002-08-09 16:14:33 +0000138 dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
139 else:
140 dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
141
142 # As a last resort, the current directory.
143 try:
144 dirlist.append(_os.getcwd())
145 except (AttributeError, _os.error):
146 dirlist.append(_os.curdir)
147
148 return dirlist
Tim Petersa0d55de2002-08-09 18:01:01 +0000149
Guido van Rossum0e548712002-08-09 16:14:33 +0000150def _get_default_tempdir():
151 """Calculate the default directory to use for temporary files.
Guido van Rossume888cdc2002-08-17 14:50:24 +0000152 This routine should be called exactly once.
Guido van Rossum0e548712002-08-09 16:14:33 +0000153
154 We determine whether or not a candidate temp dir is usable by
155 trying to create and write to a file in that directory. If this
156 is successful, the test file is deleted. To prevent denial of
157 service, the name of the test file must be randomized."""
158
159 namer = _RandomNameSequence()
160 dirlist = _candidate_tempdir_list()
Guido van Rossum0e548712002-08-09 16:14:33 +0000161
162 for dir in dirlist:
163 if dir != _os.curdir:
164 dir = _os.path.normcase(_os.path.abspath(dir))
165 # Try only a few names per directory.
Guido van Rossum805365e2007-05-07 22:24:25 +0000166 for seq in range(100):
Georg Brandla18af4e2007-04-21 15:47:16 +0000167 name = next(namer)
Guido van Rossum0e548712002-08-09 16:14:33 +0000168 filename = _os.path.join(dir, name)
169 try:
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000170 fd = _os.open(filename, _bin_openflags, 0o600)
Guido van Rossum5424df22007-08-13 19:06:38 +0000171 fp = _io.open(fd, 'wb')
172 fp.write(b'blat')
Tim Petersb90f89a2001-01-15 03:26:36 +0000173 fp.close()
Guido van Rossum0e548712002-08-09 16:14:33 +0000174 _os.unlink(filename)
175 del fp, fd
176 return dir
Guido van Rossumb940e112007-01-10 16:19:56 +0000177 except (OSError, IOError) as e:
Georg Brandl7816e512007-10-22 12:42:46 +0000178 if e.args[0] != _errno.EEXIST:
Guido van Rossum0e548712002-08-09 16:14:33 +0000179 break # no point trying more names in this directory
180 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000181 raise IOError(_errno.ENOENT,
182 "No usable temporary directory found in %s" % dirlist)
Guido van Rossum0e548712002-08-09 16:14:33 +0000183
Guido van Rossume888cdc2002-08-17 14:50:24 +0000184_name_sequence = None
185
Guido van Rossum0e548712002-08-09 16:14:33 +0000186def _get_candidate_names():
187 """Common setup sequence for all user-callable interfaces."""
188
Guido van Rossume888cdc2002-08-17 14:50:24 +0000189 global _name_sequence
190 if _name_sequence is None:
191 _once_lock.acquire()
192 try:
193 if _name_sequence is None:
194 _name_sequence = _RandomNameSequence()
195 finally:
196 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000197 return _name_sequence
Guido van Rossum41f95031992-03-31 19:02:01 +0000198
199
Guido van Rossum0e548712002-08-09 16:14:33 +0000200def _mkstemp_inner(dir, pre, suf, flags):
201 """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
Tim Peters9fadfb02001-01-13 03:04:02 +0000202
Guido van Rossum0e548712002-08-09 16:14:33 +0000203 names = _get_candidate_names()
204
Guido van Rossum805365e2007-05-07 22:24:25 +0000205 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000206 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000207 file = _os.path.join(dir, pre + name + suf)
208 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000209 fd = _os.open(file, flags, 0o600)
Guido van Rossum0e548712002-08-09 16:14:33 +0000210 _set_cloexec(fd)
Martin v. Löwisd6625482003-10-12 17:37:01 +0000211 return (fd, _os.path.abspath(file))
Guido van Rossumb940e112007-01-10 16:19:56 +0000212 except OSError as e:
Guido van Rossum0e548712002-08-09 16:14:33 +0000213 if e.errno == _errno.EEXIST:
214 continue # try again
215 raise
216
Collin Winterce36ad82007-08-30 01:19:48 +0000217 raise IOError(_errno.EEXIST, "No usable temporary file name found")
Tim Petersa0d55de2002-08-09 18:01:01 +0000218
Guido van Rossum0e548712002-08-09 16:14:33 +0000219
220# User visible interfaces.
Guido van Rossumb0e57181998-10-14 20:27:05 +0000221
Guido van Rossum41f95031992-03-31 19:02:01 +0000222def gettempprefix():
Guido van Rossum0e548712002-08-09 16:14:33 +0000223 """Accessor for tempdir.template."""
224 return template
Tim Peters9fadfb02001-01-13 03:04:02 +0000225
Guido van Rossume888cdc2002-08-17 14:50:24 +0000226tempdir = None
227
Guido van Rossum0e548712002-08-09 16:14:33 +0000228def gettempdir():
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000229 """Accessor for tempfile.tempdir."""
Guido van Rossume888cdc2002-08-17 14:50:24 +0000230 global tempdir
231 if tempdir is None:
232 _once_lock.acquire()
233 try:
234 if tempdir is None:
235 tempdir = _get_default_tempdir()
236 finally:
237 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000238 return tempdir
239
Guido van Rossume888cdc2002-08-17 14:50:24 +0000240def mkstemp(suffix="", prefix=template, dir=None, text=False):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000241 """User-callable function to create and return a unique temporary
Guido van Rossum0e548712002-08-09 16:14:33 +0000242 file. The return value is a pair (fd, name) where fd is the
243 file descriptor returned by os.open, and name is the filename.
244
245 If 'suffix' is specified, the file name will end with that suffix,
246 otherwise there will be no suffix.
247
248 If 'prefix' is specified, the file name will begin with that prefix,
249 otherwise a default prefix is used.
250
251 If 'dir' is specified, the file will be created in that directory,
252 otherwise a default directory is used.
253
Tim Peters04490bf2002-08-14 15:41:26 +0000254 If 'text' is specified and true, the file is opened in text
255 mode. Else (the default) the file is opened in binary mode. On
256 some operating systems, this makes no difference.
Guido van Rossum0e548712002-08-09 16:14:33 +0000257
258 The file is readable and writable only by the creating user ID.
259 If the operating system uses permission bits to indicate whether a
260 file is executable, the file is executable by no one. The file
261 descriptor is not inherited by children of this process.
262
263 Caller is responsible for deleting the file when done with it.
Tim Peters9fadfb02001-01-13 03:04:02 +0000264 """
265
Guido van Rossume888cdc2002-08-17 14:50:24 +0000266 if dir is None:
267 dir = gettempdir()
268
Tim Peters04490bf2002-08-14 15:41:26 +0000269 if text:
Guido van Rossum0e548712002-08-09 16:14:33 +0000270 flags = _text_openflags
Tim Peters04490bf2002-08-14 15:41:26 +0000271 else:
272 flags = _bin_openflags
Guido van Rossum0e548712002-08-09 16:14:33 +0000273
274 return _mkstemp_inner(dir, prefix, suffix, flags)
Guido van Rossumcff34541992-01-14 18:31:56 +0000275
Guido van Rossumeee94981991-11-12 15:38:08 +0000276
Guido van Rossume888cdc2002-08-17 14:50:24 +0000277def mkdtemp(suffix="", prefix=template, dir=None):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000278 """User-callable function to create and return a unique temporary
Guido van Rossum0e548712002-08-09 16:14:33 +0000279 directory. The return value is the pathname of the directory.
280
Tim Peters04490bf2002-08-14 15:41:26 +0000281 Arguments are as for mkstemp, except that the 'text' argument is
Guido van Rossum0e548712002-08-09 16:14:33 +0000282 not accepted.
283
284 The directory is readable, writable, and searchable only by the
285 creating user.
286
287 Caller is responsible for deleting the directory when done with it.
288 """
289
Guido van Rossume888cdc2002-08-17 14:50:24 +0000290 if dir is None:
291 dir = gettempdir()
292
Guido van Rossum0e548712002-08-09 16:14:33 +0000293 names = _get_candidate_names()
Tim Petersa0d55de2002-08-09 18:01:01 +0000294
Guido van Rossum805365e2007-05-07 22:24:25 +0000295 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000296 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000297 file = _os.path.join(dir, prefix + name + suffix)
298 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000299 _os.mkdir(file, 0o700)
Guido van Rossum0e548712002-08-09 16:14:33 +0000300 return file
Guido van Rossumb940e112007-01-10 16:19:56 +0000301 except OSError as e:
Guido van Rossum0e548712002-08-09 16:14:33 +0000302 if e.errno == _errno.EEXIST:
303 continue # try again
304 raise
305
Collin Winterce36ad82007-08-30 01:19:48 +0000306 raise IOError(_errno.EEXIST, "No usable temporary directory name found")
Guido van Rossum0e548712002-08-09 16:14:33 +0000307
Guido van Rossume888cdc2002-08-17 14:50:24 +0000308def mktemp(suffix="", prefix=template, dir=None):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000309 """User-callable function to return a unique temporary file name. The
Guido van Rossum0e548712002-08-09 16:14:33 +0000310 file is not created.
311
Tim Peters04490bf2002-08-14 15:41:26 +0000312 Arguments are as for mkstemp, except that the 'text' argument is
Guido van Rossum0e548712002-08-09 16:14:33 +0000313 not accepted.
314
315 This function is unsafe and should not be used. The file name
316 refers to a file that did not exist at some point, but by the time
317 you get around to creating it, someone else may have beaten you to
318 the punch.
319 """
320
Guido van Rossum44f602d2002-11-22 15:56:29 +0000321## from warnings import warn as _warn
322## _warn("mktemp is a potential security risk to your program",
323## RuntimeWarning, stacklevel=2)
Guido van Rossum0e548712002-08-09 16:14:33 +0000324
Guido van Rossume888cdc2002-08-17 14:50:24 +0000325 if dir is None:
326 dir = gettempdir()
327
Guido van Rossum0e548712002-08-09 16:14:33 +0000328 names = _get_candidate_names()
Guido van Rossum805365e2007-05-07 22:24:25 +0000329 for seq in range(TMP_MAX):
Georg Brandla18af4e2007-04-21 15:47:16 +0000330 name = next(names)
Guido van Rossum0e548712002-08-09 16:14:33 +0000331 file = _os.path.join(dir, prefix + name + suffix)
Guido van Rossumb256159392003-11-10 02:16:36 +0000332 if not _exists(file):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000333 return file
Guido van Rossumca549821997-08-12 18:00:12 +0000334
Collin Winterce36ad82007-08-30 01:19:48 +0000335 raise IOError(_errno.EEXIST, "No usable temporary filename found")
Guido van Rossumca549821997-08-12 18:00:12 +0000336
Christian Heimes3ecfea712008-02-09 20:51:34 +0000337
Guido van Rossum0e548712002-08-09 16:14:33 +0000338class _TemporaryFileWrapper:
Guido van Rossumca549821997-08-12 18:00:12 +0000339 """Temporary file wrapper
340
Guido van Rossum0e548712002-08-09 16:14:33 +0000341 This class provides a wrapper around files opened for
342 temporary use. In particular, it seeks to automatically
343 remove the file when it is no longer needed.
Guido van Rossumca549821997-08-12 18:00:12 +0000344 """
Tim Petersa255a722001-12-18 22:32:40 +0000345
Guido van Rossumd8faa362007-04-27 19:54:29 +0000346 def __init__(self, file, name, delete=True):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000347 self.file = file
Guido van Rossum0e548712002-08-09 16:14:33 +0000348 self.name = name
Tim Peters6ef966e2002-11-21 15:48:33 +0000349 self.close_called = False
Guido van Rossumd8faa362007-04-27 19:54:29 +0000350 self.delete = delete
Guido van Rossumca549821997-08-12 18:00:12 +0000351
Guido van Rossumca549821997-08-12 18:00:12 +0000352 def __getattr__(self, name):
Christian Heimes3ecfea712008-02-09 20:51:34 +0000353 # Attribute lookups are delegated to the underlying file
354 # and cached for non-numeric results
355 # (i.e. methods are cached, closed and friends are not)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000356 file = self.__dict__['file']
357 a = getattr(file, name)
Christian Heimes3ecfea712008-02-09 20:51:34 +0000358 if not isinstance(a, int):
Guido van Rossum6b708d51999-06-01 18:55:36 +0000359 setattr(self, name, a)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000360 return a
Guido van Rossumca549821997-08-12 18:00:12 +0000361
Christian Heimes3ecfea712008-02-09 20:51:34 +0000362 # The underlying __enter__ method returns the wrong object
363 # (self.file) so override it to return the wrapper
364 def __enter__(self):
365 self.file.__enter__()
366 return self
367
Christian Heimes36d1f8e2008-02-28 22:21:11 +0000368 # iter() doesn't use __getattr__ to find the __iter__ method
Christian Heimesc83b6292008-02-28 21:10:17 +0000369 def __iter__(self):
Christian Heimes36d1f8e2008-02-28 22:21:11 +0000370 return iter(self.file)
Christian Heimesc83b6292008-02-28 21:10:17 +0000371
Guido van Rossum0e548712002-08-09 16:14:33 +0000372 # NT provides delete-on-close as a primitive, so we don't need
373 # the wrapper to do anything special. We still use it so that
374 # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
375 if _os.name != 'nt':
Guido van Rossum0e548712002-08-09 16:14:33 +0000376 # Cache the unlinker so we don't get spurious errors at
377 # shutdown when the module-level "os" is None'd out. Note
378 # that this must be referenced as self.unlink, because the
379 # name TemporaryFileWrapper may also get None'd out before
380 # __del__ is called.
381 unlink = _os.unlink
Tim Peters1baa22a2001-01-12 10:02:46 +0000382
Guido van Rossum0e548712002-08-09 16:14:33 +0000383 def close(self):
384 if not self.close_called:
Tim Peters6ef966e2002-11-21 15:48:33 +0000385 self.close_called = True
Guido van Rossum0e548712002-08-09 16:14:33 +0000386 self.file.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000387 if self.delete:
388 self.unlink(self.name)
Tim Peters1baa22a2001-01-12 10:02:46 +0000389
Guido van Rossum0e548712002-08-09 16:14:33 +0000390 def __del__(self):
391 self.close()
Tim Peters1baa22a2001-01-12 10:02:46 +0000392
Christian Heimes3ecfea712008-02-09 20:51:34 +0000393 # Need to trap __exit__ as well to ensure the file gets
394 # deleted when used in a with statement
395 def __exit__(self, exc, value, tb):
396 result = self.file.__exit__(exc, value, tb)
397 self.close()
398 return result
Benjamin Peterson98d23f22009-06-30 22:27:25 +0000399 else:
400 def __exit__(self, exc, value, tb):
Benjamin Peterson3f5de132009-07-01 15:47:07 +0000401 self.file.__exit__(exc, value, tb)
Christian Heimes3ecfea712008-02-09 20:51:34 +0000402
403
Guido van Rossumf0c74162007-08-28 03:29:45 +0000404def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None,
405 newline=None, suffix="", prefix=template,
406 dir=None, delete=True):
Guido van Rossum0e548712002-08-09 16:14:33 +0000407 """Create and return a temporary file.
408 Arguments:
409 'prefix', 'suffix', 'dir' -- as for mkstemp.
Guido van Rossumf0c74162007-08-28 03:29:45 +0000410 'mode' -- the mode argument to io.open (default "w+b").
411 'buffering' -- the buffer size argument to io.open (default -1).
412 'encoding' -- the encoding argument to io.open (default None)
413 'newline' -- the newline argument to io.open (default None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000414 'delete' -- whether the file is deleted on close (default True).
Guido van Rossum0e548712002-08-09 16:14:33 +0000415 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000416
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000417 Returns an object with a file-like interface; the name of the file
418 is accessible as file.name. The file will be automatically deleted
Guido van Rossumd8faa362007-04-27 19:54:29 +0000419 when it is closed unless the 'delete' argument is set to False.
Guido van Rossum0e548712002-08-09 16:14:33 +0000420 """
Tim Peters1baa22a2001-01-12 10:02:46 +0000421
Guido van Rossume888cdc2002-08-17 14:50:24 +0000422 if dir is None:
423 dir = gettempdir()
424
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000425 flags = _bin_openflags
Tim Peters1baa22a2001-01-12 10:02:46 +0000426
Guido van Rossum0e548712002-08-09 16:14:33 +0000427 # Setting O_TEMPORARY in the flags causes the OS to delete
428 # the file when it is closed. This is only supported by Windows.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000429 if _os.name == 'nt' and delete:
Guido van Rossum0e548712002-08-09 16:14:33 +0000430 flags |= _os.O_TEMPORARY
Tim Peters1baa22a2001-01-12 10:02:46 +0000431
Guido van Rossum0e548712002-08-09 16:14:33 +0000432 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000433 file = _io.open(fd, mode, buffering=buffering,
434 newline=newline, encoding=encoding)
435
Guido van Rossumd8faa362007-04-27 19:54:29 +0000436 return _TemporaryFileWrapper(file, name, delete)
Guido van Rossum0e548712002-08-09 16:14:33 +0000437
Jason Tishler80c02af2002-08-14 15:10:09 +0000438if _os.name != 'posix' or _os.sys.platform == 'cygwin':
439 # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
440 # while it is open.
Guido van Rossum0e548712002-08-09 16:14:33 +0000441 TemporaryFile = NamedTemporaryFile
Tim Peters1baa22a2001-01-12 10:02:46 +0000442
443else:
Guido van Rossumf0c74162007-08-28 03:29:45 +0000444 def TemporaryFile(mode='w+b', buffering=-1, encoding=None,
445 newline=None, suffix="", prefix=template,
446 dir=None):
Guido van Rossum0e548712002-08-09 16:14:33 +0000447 """Create and return a temporary file.
448 Arguments:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000449 'prefix', 'suffix', 'dir' -- as for mkstemp.
Guido van Rossumf0c74162007-08-28 03:29:45 +0000450 'mode' -- the mode argument to io.open (default "w+b").
451 'buffering' -- the buffer size argument to io.open (default -1).
452 'encoding' -- the encoding argument to io.open (default None)
453 'newline' -- the newline argument to io.open (default None)
Guido van Rossum0e548712002-08-09 16:14:33 +0000454 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000455
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000456 Returns an object with a file-like interface. The file has no
457 name, and will cease to exist when it is closed.
Guido van Rossum0e548712002-08-09 16:14:33 +0000458 """
459
Guido van Rossume888cdc2002-08-17 14:50:24 +0000460 if dir is None:
461 dir = gettempdir()
462
Amaury Forgeot d'Arc7d0bddd2009-11-30 00:08:56 +0000463 flags = _bin_openflags
Guido van Rossum0e548712002-08-09 16:14:33 +0000464
465 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
466 try:
467 _os.unlink(name)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000468 return _io.open(fd, mode, buffering=buffering,
469 newline=newline, encoding=encoding)
Guido van Rossum0e548712002-08-09 16:14:33 +0000470 except:
471 _os.close(fd)
472 raise
Guido van Rossumd8faa362007-04-27 19:54:29 +0000473
474class SpooledTemporaryFile:
475 """Temporary file wrapper, specialized to switch from
476 StringIO to a real file when it exceeds a certain size or
477 when a fileno is needed.
478 """
479 _rolled = False
480
Guido van Rossumf0c74162007-08-28 03:29:45 +0000481 def __init__(self, max_size=0, mode='w+b', buffering=-1,
482 encoding=None, newline=None,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000483 suffix="", prefix=template, dir=None):
Guido van Rossum9a634702007-07-09 10:24:45 +0000484 if 'b' in mode:
485 self._file = _io.BytesIO()
486 else:
Guido van Rossum5d212552007-10-29 16:42:51 +0000487 # Setting newline="\n" avoids newline translation;
488 # this is important because otherwise on Windows we'd
Guido van Rossum98297ee2007-11-06 21:34:58 +0000489 # hget double newline translation upon rollover().
Alexandre Vassalotti3ade6f92008-06-12 01:13:54 +0000490 self._file = _io.StringIO(newline="\n")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000491 self._max_size = max_size
492 self._rolled = False
Guido van Rossumf0c74162007-08-28 03:29:45 +0000493 self._TemporaryFileArgs = {'mode': mode, 'buffering': buffering,
494 'suffix': suffix, 'prefix': prefix,
495 'encoding': encoding, 'newline': newline,
496 'dir': dir}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000497
498 def _check(self, file):
499 if self._rolled: return
500 max_size = self._max_size
501 if max_size and file.tell() > max_size:
502 self.rollover()
503
504 def rollover(self):
505 if self._rolled: return
506 file = self._file
Guido van Rossumf0c74162007-08-28 03:29:45 +0000507 newfile = self._file = TemporaryFile(**self._TemporaryFileArgs)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000508 del self._TemporaryFileArgs
509
510 newfile.write(file.getvalue())
511 newfile.seek(file.tell(), 0)
512
513 self._rolled = True
514
Christian Heimes3ecfea712008-02-09 20:51:34 +0000515 # The method caching trick from NamedTemporaryFile
516 # won't work here, because _file may change from a
517 # _StringIO instance to a real file. So we list
518 # all the methods directly.
519
520 # Context management protocol
521 def __enter__(self):
522 if self._file.closed:
523 raise ValueError("Cannot enter context with closed file")
524 return self
525
526 def __exit__(self, exc, value, tb):
527 self._file.close()
528
Guido van Rossumd8faa362007-04-27 19:54:29 +0000529 # file protocol
530 def __iter__(self):
531 return self._file.__iter__()
532
533 def close(self):
534 self._file.close()
535
536 @property
537 def closed(self):
538 return self._file.closed
539
540 @property
541 def encoding(self):
542 return self._file.encoding
543
544 def fileno(self):
545 self.rollover()
546 return self._file.fileno()
547
548 def flush(self):
549 self._file.flush()
550
551 def isatty(self):
552 return self._file.isatty()
553
554 @property
555 def mode(self):
556 return self._file.mode
557
558 @property
559 def name(self):
560 return self._file.name
561
562 @property
563 def newlines(self):
564 return self._file.newlines
565
566 def next(self):
567 return self._file.next
568
569 def read(self, *args):
570 return self._file.read(*args)
571
572 def readline(self, *args):
573 return self._file.readline(*args)
574
575 def readlines(self, *args):
576 return self._file.readlines(*args)
577
578 def seek(self, *args):
579 self._file.seek(*args)
580
581 @property
582 def softspace(self):
583 return self._file.softspace
584
585 def tell(self):
586 return self._file.tell()
587
588 def truncate(self):
589 self._file.truncate()
590
591 def write(self, s):
592 file = self._file
593 rv = file.write(s)
594 self._check(file)
595 return rv
596
597 def writelines(self, iterable):
598 file = self._file
599 rv = file.writelines(iterable)
600 self._check(file)
601 return rv
602
603 def xreadlines(self, *args):
604 return self._file.xreadlines(*args)
Nick Coghlan543af752010-10-24 11:23:25 +0000605
606
607class TemporaryDirectory(object):
608 """Create and return a temporary directory. This has the same
609 behavior as mkdtemp but can be used as a context manager. For
610 example:
611
612 with TemporaryDirectory() as tmpdir:
613 ...
614
615 Upon exiting the context, the directory and everthing contained
616 in it are removed.
617 """
618
619 def __init__(self, suffix="", prefix=template, dir=None):
Georg Brandlab3734f2010-12-11 19:10:30 +0000620 # cleanup() needs this and is called even when mkdtemp fails
621 self._closed = True
Nick Coghlan543af752010-10-24 11:23:25 +0000622 self.name = mkdtemp(suffix, prefix, dir)
623 self._closed = False
624
625 def __enter__(self):
626 return self.name
627
628 def cleanup(self):
629 if not self._closed:
630 self._rmtree(self.name)
631 self._closed = True
632
633 def __exit__(self, exc, value, tb):
634 self.cleanup()
635
636 __del__ = cleanup
637
638
639 # XXX (ncoghlan): The following code attempts to make
640 # this class tolerant of the module nulling out process
641 # that happens during CPython interpreter shutdown
642 # Alas, it doesn't actually manage it. See issue #10188
643 _listdir = staticmethod(_os.listdir)
644 _path_join = staticmethod(_os.path.join)
645 _isdir = staticmethod(_os.path.isdir)
646 _remove = staticmethod(_os.remove)
647 _rmdir = staticmethod(_os.rmdir)
648 _os_error = _os.error
649
650 def _rmtree(self, path):
651 # Essentially a stripped down version of shutil.rmtree. We can't
652 # use globals because they may be None'ed out at shutdown.
653 for name in self._listdir(path):
654 fullname = self._path_join(path, name)
655 try:
656 isdir = self._isdir(fullname)
657 except self._os_error:
658 isdir = False
659 if isdir:
660 self._rmtree(fullname)
661 else:
662 try:
663 self._remove(fullname)
664 except self._os_error:
665 pass
666 try:
667 self._rmdir(path)
668 except self._os_error:
669 pass