blob: fbda8ebeb732ad4a1423647da16cee8e79ea4a68 [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
Yury Selivanov6e7c1402014-09-26 17:07:39 -04004creating temporary files and directories. All of the interfaces
5provided by this module can be used without fear of race conditions
6except for 'mktemp'. 'mktemp' is subject to race conditions and
7should not be used; it is provided for backward compatibility 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
Collin Wintera8785cc2007-03-19 18:52:08 +000022 "SpooledTemporaryFile",
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
Serhiy Storchaka0127de02013-02-13 00:34:46 +020032import 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 Rossum0e548712002-08-09 16:14:33 +000037try:
Neal Norwitz0d4c06e2007-04-25 06:30:05 +000038 from cStringIO import StringIO as _StringIO
Skip Montanaroea59a842008-04-27 22:49:56 +000039except ImportError:
Neal Norwitz0d4c06e2007-04-25 06:30:05 +000040 from StringIO import StringIO as _StringIO
Collin Wintera8785cc2007-03-19 18:52:08 +000041
42try:
Guido van Rossum0e548712002-08-09 16:14:33 +000043 import fcntl as _fcntl
Tim Peters90ee7eb2004-07-18 23:58:17 +000044except ImportError:
Tim Peters291f14e2003-07-22 02:50:01 +000045 def _set_cloexec(fd):
46 pass
47else:
Guido van Rossum0e548712002-08-09 16:14:33 +000048 def _set_cloexec(fd):
Tim Peters90ee7eb2004-07-18 23:58:17 +000049 try:
50 flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0)
51 except IOError:
52 pass
Alex Martellif09994e2003-11-09 16:44:09 +000053 else:
Guido van Rossum0e548712002-08-09 16:14:33 +000054 # flags read successfully, modify
55 flags |= _fcntl.FD_CLOEXEC
56 _fcntl.fcntl(fd, _fcntl.F_SETFD, flags)
Tim Peters291f14e2003-07-22 02:50:01 +000057
Guido van Rossum0e548712002-08-09 16:14:33 +000058
59try:
60 import thread as _thread
Guido van Rossuma0934242002-12-30 22:36:09 +000061except ImportError:
62 import dummy_thread as _thread
63_allocate_lock = _thread.allocate_lock
Guido van Rossum0e548712002-08-09 16:14:33 +000064
65_text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL
Tim Petersa0d55de2002-08-09 18:01:01 +000066if hasattr(_os, 'O_NOINHERIT'):
67 _text_openflags |= _os.O_NOINHERIT
68if hasattr(_os, 'O_NOFOLLOW'):
69 _text_openflags |= _os.O_NOFOLLOW
Guido van Rossum0e548712002-08-09 16:14:33 +000070
71_bin_openflags = _text_openflags
Tim Petersa0d55de2002-08-09 18:01:01 +000072if hasattr(_os, 'O_BINARY'):
73 _bin_openflags |= _os.O_BINARY
Guido van Rossum0e548712002-08-09 16:14:33 +000074
75if hasattr(_os, 'TMP_MAX'):
76 TMP_MAX = _os.TMP_MAX
77else:
78 TMP_MAX = 10000
79
Tim Petersbd7b4c72002-08-13 23:33:56 +000080template = "tmp"
Guido van Rossum0e548712002-08-09 16:14:33 +000081
Guido van Rossum0e548712002-08-09 16:14:33 +000082# Internal routines.
83
84_once_lock = _allocate_lock()
85
Guido van Rossumb256159392003-11-10 02:16:36 +000086if hasattr(_os, "lstat"):
87 _stat = _os.lstat
88elif hasattr(_os, "stat"):
89 _stat = _os.stat
90else:
91 # Fallback. All we need is something that raises os.error if the
92 # file doesn't exist.
93 def _stat(fn):
94 try:
95 f = open(fn)
96 except IOError:
97 raise _os.error
98 f.close()
99
100def _exists(fn):
101 try:
102 _stat(fn)
103 except _os.error:
104 return False
105 else:
106 return True
107
Guido van Rossum0e548712002-08-09 16:14:33 +0000108class _RandomNameSequence:
109 """An instance of _RandomNameSequence generates an endless
110 sequence of unpredictable strings which can safely be incorporated
111 into file names. Each string is six characters long. Multiple
112 threads can safely use the same instance at the same time.
113
114 _RandomNameSequence is an iterator."""
115
Tim Peters97701b52002-11-21 15:59:59 +0000116 characters = ("abcdefghijklmnopqrstuvwxyz" +
117 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
Collin Winter9b2a1092007-03-08 22:16:25 +0000118 "0123456789_")
Guido van Rossum0e548712002-08-09 16:14:33 +0000119
120 def __init__(self):
121 self.mutex = _allocate_lock()
Guido van Rossum0e548712002-08-09 16:14:33 +0000122 self.normcase = _os.path.normcase
Tim Peters97701b52002-11-21 15:59:59 +0000123
Antoine Pitroua5d5bb92011-11-25 21:28:15 +0100124 @property
125 def rng(self):
126 cur_pid = _os.getpid()
127 if cur_pid != getattr(self, '_rng_pid', None):
128 self._rng = _Random()
129 self._rng_pid = cur_pid
130 return self._rng
131
Guido van Rossum0e548712002-08-09 16:14:33 +0000132 def __iter__(self):
133 return self
134
135 def next(self):
136 m = self.mutex
137 c = self.characters
Tim Peters97701b52002-11-21 15:59:59 +0000138 choose = self.rng.choice
Guido van Rossum0e548712002-08-09 16:14:33 +0000139
Tim Peters97701b52002-11-21 15:59:59 +0000140 m.acquire()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000141 try:
Tim Peters97701b52002-11-21 15:59:59 +0000142 letters = [choose(c) for dummy in "123456"]
Guido van Rossum0e548712002-08-09 16:14:33 +0000143 finally:
144 m.release()
145
Tim Peters97701b52002-11-21 15:59:59 +0000146 return self.normcase(''.join(letters))
Guido van Rossum0e548712002-08-09 16:14:33 +0000147
148def _candidate_tempdir_list():
149 """Generate a list of candidate temporary directories which
150 _get_default_tempdir will try."""
151
152 dirlist = []
153
154 # First, try the environment.
155 for envname in 'TMPDIR', 'TEMP', 'TMP':
156 dirname = _os.getenv(envname)
157 if dirname: dirlist.append(dirname)
158
159 # Failing that, try OS-specific locations.
Ronald Oussoren81af68e2008-05-12 11:24:33 +0000160 if _os.name == 'riscos':
Guido van Rossum0e548712002-08-09 16:14:33 +0000161 dirname = _os.getenv('Wimp$ScrapDir')
162 if dirname: dirlist.append(dirname)
163 elif _os.name == 'nt':
164 dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
165 else:
166 dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
167
168 # As a last resort, the current directory.
169 try:
170 dirlist.append(_os.getcwd())
171 except (AttributeError, _os.error):
172 dirlist.append(_os.curdir)
173
174 return dirlist
Tim Petersa0d55de2002-08-09 18:01:01 +0000175
Guido van Rossum0e548712002-08-09 16:14:33 +0000176def _get_default_tempdir():
177 """Calculate the default directory to use for temporary files.
Guido van Rossume888cdc2002-08-17 14:50:24 +0000178 This routine should be called exactly once.
Guido van Rossum0e548712002-08-09 16:14:33 +0000179
180 We determine whether or not a candidate temp dir is usable by
181 trying to create and write to a file in that directory. If this
182 is successful, the test file is deleted. To prevent denial of
183 service, the name of the test file must be randomized."""
184
185 namer = _RandomNameSequence()
186 dirlist = _candidate_tempdir_list()
187 flags = _text_openflags
188
189 for dir in dirlist:
190 if dir != _os.curdir:
191 dir = _os.path.normcase(_os.path.abspath(dir))
192 # Try only a few names per directory.
193 for seq in xrange(100):
194 name = namer.next()
195 filename = _os.path.join(dir, name)
196 try:
Serhiy Storchaka0127de02013-02-13 00:34:46 +0200197 fd = _os.open(filename, flags, 0o600)
198 try:
199 try:
Serhiy Storchaka7d360032013-02-13 00:59:11 +0200200 with _io.open(fd, 'wb', closefd=False) as fp:
201 fp.write(b'blat')
Serhiy Storchaka0127de02013-02-13 00:34:46 +0200202 finally:
203 _os.close(fd)
204 finally:
205 _os.unlink(filename)
Guido van Rossum0e548712002-08-09 16:14:33 +0000206 return dir
Serhiy Storchaka0127de02013-02-13 00:34:46 +0200207 except (OSError, IOError) as e:
Ezio Melotti4dbcec92013-02-23 08:16:07 +0200208 if e.args[0] != _errno.EEXIST:
Guido van Rossum0e548712002-08-09 16:14:33 +0000209 break # no point trying more names in this directory
210 pass
211 raise IOError, (_errno.ENOENT,
212 ("No usable temporary directory found in %s" % dirlist))
213
Guido van Rossume888cdc2002-08-17 14:50:24 +0000214_name_sequence = None
215
Guido van Rossum0e548712002-08-09 16:14:33 +0000216def _get_candidate_names():
217 """Common setup sequence for all user-callable interfaces."""
218
Guido van Rossume888cdc2002-08-17 14:50:24 +0000219 global _name_sequence
220 if _name_sequence is None:
221 _once_lock.acquire()
222 try:
223 if _name_sequence is None:
224 _name_sequence = _RandomNameSequence()
225 finally:
226 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000227 return _name_sequence
Guido van Rossum41f95031992-03-31 19:02:01 +0000228
229
Guido van Rossum0e548712002-08-09 16:14:33 +0000230def _mkstemp_inner(dir, pre, suf, flags):
231 """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
Tim Peters9fadfb02001-01-13 03:04:02 +0000232
Guido van Rossum0e548712002-08-09 16:14:33 +0000233 names = _get_candidate_names()
234
235 for seq in xrange(TMP_MAX):
236 name = names.next()
237 file = _os.path.join(dir, pre + name + suf)
238 try:
239 fd = _os.open(file, flags, 0600)
240 _set_cloexec(fd)
Martin v. Löwisd6625482003-10-12 17:37:01 +0000241 return (fd, _os.path.abspath(file))
Guido van Rossum0e548712002-08-09 16:14:33 +0000242 except OSError, e:
243 if e.errno == _errno.EEXIST:
244 continue # try again
Eli Bendersky8c7e9252013-09-06 06:17:15 -0700245 if _os.name == 'nt' and e.errno == _errno.EACCES:
246 # On windows, when a directory with the chosen name already
247 # exists, EACCES error code is returned instead of EEXIST.
248 continue
Guido van Rossum0e548712002-08-09 16:14:33 +0000249 raise
250
251 raise IOError, (_errno.EEXIST, "No usable temporary file name found")
Tim Petersa0d55de2002-08-09 18:01:01 +0000252
Guido van Rossum0e548712002-08-09 16:14:33 +0000253
254# User visible interfaces.
Guido van Rossumb0e57181998-10-14 20:27:05 +0000255
Guido van Rossum41f95031992-03-31 19:02:01 +0000256def gettempprefix():
Guido van Rossum0e548712002-08-09 16:14:33 +0000257 """Accessor for tempdir.template."""
258 return template
Tim Peters9fadfb02001-01-13 03:04:02 +0000259
Guido van Rossume888cdc2002-08-17 14:50:24 +0000260tempdir = None
261
Guido van Rossum0e548712002-08-09 16:14:33 +0000262def gettempdir():
Skip Montanaroea59a842008-04-27 22:49:56 +0000263 """Accessor for tempfile.tempdir."""
Guido van Rossume888cdc2002-08-17 14:50:24 +0000264 global tempdir
265 if tempdir is None:
266 _once_lock.acquire()
267 try:
268 if tempdir is None:
269 tempdir = _get_default_tempdir()
270 finally:
271 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000272 return tempdir
273
Guido van Rossume888cdc2002-08-17 14:50:24 +0000274def mkstemp(suffix="", prefix=template, dir=None, text=False):
Skip Montanaroea59a842008-04-27 22:49:56 +0000275 """User-callable function to create and return a unique temporary
Guido van Rossum0e548712002-08-09 16:14:33 +0000276 file. The return value is a pair (fd, name) where fd is the
277 file descriptor returned by os.open, and name is the filename.
278
279 If 'suffix' is specified, the file name will end with that suffix,
280 otherwise there will be no suffix.
281
282 If 'prefix' is specified, the file name will begin with that prefix,
283 otherwise a default prefix is used.
284
285 If 'dir' is specified, the file will be created in that directory,
286 otherwise a default directory is used.
287
Tim Peters04490bf2002-08-14 15:41:26 +0000288 If 'text' is specified and true, the file is opened in text
289 mode. Else (the default) the file is opened in binary mode. On
290 some operating systems, this makes no difference.
Guido van Rossum0e548712002-08-09 16:14:33 +0000291
292 The file is readable and writable only by the creating user ID.
293 If the operating system uses permission bits to indicate whether a
294 file is executable, the file is executable by no one. The file
295 descriptor is not inherited by children of this process.
296
297 Caller is responsible for deleting the file when done with it.
Tim Peters9fadfb02001-01-13 03:04:02 +0000298 """
299
Guido van Rossume888cdc2002-08-17 14:50:24 +0000300 if dir is None:
301 dir = gettempdir()
302
Tim Peters04490bf2002-08-14 15:41:26 +0000303 if text:
Guido van Rossum0e548712002-08-09 16:14:33 +0000304 flags = _text_openflags
Tim Peters04490bf2002-08-14 15:41:26 +0000305 else:
306 flags = _bin_openflags
Guido van Rossum0e548712002-08-09 16:14:33 +0000307
308 return _mkstemp_inner(dir, prefix, suffix, flags)
Guido van Rossumcff34541992-01-14 18:31:56 +0000309
Guido van Rossumeee94981991-11-12 15:38:08 +0000310
Guido van Rossume888cdc2002-08-17 14:50:24 +0000311def mkdtemp(suffix="", prefix=template, dir=None):
Skip Montanaroea59a842008-04-27 22:49:56 +0000312 """User-callable function to create and return a unique temporary
Guido van Rossum0e548712002-08-09 16:14:33 +0000313 directory. The return value is the pathname of the directory.
314
Tim Peters04490bf2002-08-14 15:41:26 +0000315 Arguments are as for mkstemp, except that the 'text' argument is
Guido van Rossum0e548712002-08-09 16:14:33 +0000316 not accepted.
317
318 The directory is readable, writable, and searchable only by the
319 creating user.
320
321 Caller is responsible for deleting the directory when done with it.
322 """
323
Guido van Rossume888cdc2002-08-17 14:50:24 +0000324 if dir is None:
325 dir = gettempdir()
326
Guido van Rossum0e548712002-08-09 16:14:33 +0000327 names = _get_candidate_names()
Tim Petersa0d55de2002-08-09 18:01:01 +0000328
Guido van Rossum0e548712002-08-09 16:14:33 +0000329 for seq in xrange(TMP_MAX):
330 name = names.next()
331 file = _os.path.join(dir, prefix + name + suffix)
332 try:
333 _os.mkdir(file, 0700)
334 return file
335 except OSError, e:
336 if e.errno == _errno.EEXIST:
337 continue # try again
338 raise
339
340 raise IOError, (_errno.EEXIST, "No usable temporary directory name found")
341
Guido van Rossume888cdc2002-08-17 14:50:24 +0000342def mktemp(suffix="", prefix=template, dir=None):
Skip Montanaroea59a842008-04-27 22:49:56 +0000343 """User-callable function to return a unique temporary file name. The
Guido van Rossum0e548712002-08-09 16:14:33 +0000344 file is not created.
345
Tim Peters04490bf2002-08-14 15:41:26 +0000346 Arguments are as for mkstemp, except that the 'text' argument is
Guido van Rossum0e548712002-08-09 16:14:33 +0000347 not accepted.
348
349 This function is unsafe and should not be used. The file name
350 refers to a file that did not exist at some point, but by the time
351 you get around to creating it, someone else may have beaten you to
352 the punch.
353 """
354
Guido van Rossum44f602d2002-11-22 15:56:29 +0000355## from warnings import warn as _warn
356## _warn("mktemp is a potential security risk to your program",
357## RuntimeWarning, stacklevel=2)
Guido van Rossum0e548712002-08-09 16:14:33 +0000358
Guido van Rossume888cdc2002-08-17 14:50:24 +0000359 if dir is None:
360 dir = gettempdir()
361
Guido van Rossum0e548712002-08-09 16:14:33 +0000362 names = _get_candidate_names()
363 for seq in xrange(TMP_MAX):
364 name = names.next()
365 file = _os.path.join(dir, prefix + name + suffix)
Guido van Rossumb256159392003-11-10 02:16:36 +0000366 if not _exists(file):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000367 return file
Guido van Rossumca549821997-08-12 18:00:12 +0000368
Guido van Rossum0e548712002-08-09 16:14:33 +0000369 raise IOError, (_errno.EEXIST, "No usable temporary filename found")
Guido van Rossumca549821997-08-12 18:00:12 +0000370
Nick Coghlan97fac3e2008-02-09 15:28:09 +0000371
Guido van Rossum0e548712002-08-09 16:14:33 +0000372class _TemporaryFileWrapper:
Guido van Rossumca549821997-08-12 18:00:12 +0000373 """Temporary file wrapper
374
Guido van Rossum0e548712002-08-09 16:14:33 +0000375 This class provides a wrapper around files opened for
376 temporary use. In particular, it seeks to automatically
377 remove the file when it is no longer needed.
Guido van Rossumca549821997-08-12 18:00:12 +0000378 """
Tim Petersa255a722001-12-18 22:32:40 +0000379
Georg Brandl35ef9c12007-03-13 18:31:49 +0000380 def __init__(self, file, name, delete=True):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000381 self.file = file
Guido van Rossum0e548712002-08-09 16:14:33 +0000382 self.name = name
Tim Peters6ef966e2002-11-21 15:48:33 +0000383 self.close_called = False
Georg Brandl35ef9c12007-03-13 18:31:49 +0000384 self.delete = delete
Guido van Rossumca549821997-08-12 18:00:12 +0000385
Guido van Rossumca549821997-08-12 18:00:12 +0000386 def __getattr__(self, name):
Nick Coghlan97fac3e2008-02-09 15:28:09 +0000387 # Attribute lookups are delegated to the underlying file
388 # and cached for non-numeric results
389 # (i.e. methods are cached, closed and friends are not)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000390 file = self.__dict__['file']
391 a = getattr(file, name)
Nick Coghlan97fac3e2008-02-09 15:28:09 +0000392 if not issubclass(type(a), type(0)):
Guido van Rossum6b708d51999-06-01 18:55:36 +0000393 setattr(self, name, a)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000394 return a
Guido van Rossumca549821997-08-12 18:00:12 +0000395
Nick Coghlan97fac3e2008-02-09 15:28:09 +0000396 # The underlying __enter__ method returns the wrong object
397 # (self.file) so override it to return the wrapper
398 def __enter__(self):
399 self.file.__enter__()
400 return self
401
Guido van Rossum0e548712002-08-09 16:14:33 +0000402 # NT provides delete-on-close as a primitive, so we don't need
403 # the wrapper to do anything special. We still use it so that
404 # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
405 if _os.name != 'nt':
Guido van Rossum0e548712002-08-09 16:14:33 +0000406 # Cache the unlinker so we don't get spurious errors at
407 # shutdown when the module-level "os" is None'd out. Note
408 # that this must be referenced as self.unlink, because the
409 # name TemporaryFileWrapper may also get None'd out before
410 # __del__ is called.
411 unlink = _os.unlink
Tim Peters1baa22a2001-01-12 10:02:46 +0000412
Guido van Rossum0e548712002-08-09 16:14:33 +0000413 def close(self):
414 if not self.close_called:
Tim Peters6ef966e2002-11-21 15:48:33 +0000415 self.close_called = True
Serhiy Storchaka1aa2c0f2015-04-10 13:24:10 +0300416 try:
417 self.file.close()
418 finally:
419 if self.delete:
420 self.unlink(self.name)
Tim Peters1baa22a2001-01-12 10:02:46 +0000421
Guido van Rossum0e548712002-08-09 16:14:33 +0000422 def __del__(self):
423 self.close()
Tim Peters1baa22a2001-01-12 10:02:46 +0000424
Nick Coghlan97fac3e2008-02-09 15:28:09 +0000425 # Need to trap __exit__ as well to ensure the file gets
426 # deleted when used in a with statement
427 def __exit__(self, exc, value, tb):
428 result = self.file.__exit__(exc, value, tb)
429 self.close()
430 return result
Benjamin Peterson31f42ab2009-06-30 22:14:33 +0000431 else:
432 def __exit__(self, exc, value, tb):
Benjamin Peterson4f247672009-07-01 13:34:35 +0000433 self.file.__exit__(exc, value, tb)
Nick Coghlan97fac3e2008-02-09 15:28:09 +0000434
435
Guido van Rossum0e548712002-08-09 16:14:33 +0000436def NamedTemporaryFile(mode='w+b', bufsize=-1, suffix="",
Georg Brandl35ef9c12007-03-13 18:31:49 +0000437 prefix=template, dir=None, delete=True):
Guido van Rossum0e548712002-08-09 16:14:33 +0000438 """Create and return a temporary file.
439 Arguments:
440 'prefix', 'suffix', 'dir' -- as for mkstemp.
441 'mode' -- the mode argument to os.fdopen (default "w+b").
442 'bufsize' -- the buffer size argument to os.fdopen (default -1).
Georg Brandl35ef9c12007-03-13 18:31:49 +0000443 'delete' -- whether the file is deleted on close (default True).
Guido van Rossum0e548712002-08-09 16:14:33 +0000444 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000445
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000446 Returns an object with a file-like interface; the name of the file
447 is accessible as file.name. The file will be automatically deleted
Georg Brandl35ef9c12007-03-13 18:31:49 +0000448 when it is closed unless the 'delete' argument is set to False.
Guido van Rossum0e548712002-08-09 16:14:33 +0000449 """
Tim Peters1baa22a2001-01-12 10:02:46 +0000450
Guido van Rossume888cdc2002-08-17 14:50:24 +0000451 if dir is None:
452 dir = gettempdir()
453
Tim Petersc21ea742002-08-13 23:36:01 +0000454 if 'b' in mode:
455 flags = _bin_openflags
456 else:
457 flags = _text_openflags
Tim Peters1baa22a2001-01-12 10:02:46 +0000458
Guido van Rossum0e548712002-08-09 16:14:33 +0000459 # Setting O_TEMPORARY in the flags causes the OS to delete
460 # the file when it is closed. This is only supported by Windows.
Georg Brandl35ef9c12007-03-13 18:31:49 +0000461 if _os.name == 'nt' and delete:
Guido van Rossum0e548712002-08-09 16:14:33 +0000462 flags |= _os.O_TEMPORARY
Tim Peters1baa22a2001-01-12 10:02:46 +0000463
Guido van Rossum0e548712002-08-09 16:14:33 +0000464 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
Victor Stinner367f5d32014-03-25 09:08:16 +0100465 try:
466 file = _os.fdopen(fd, mode, bufsize)
467 return _TemporaryFileWrapper(file, name, delete)
Victor Stinnerdd48b902014-03-25 09:10:59 +0100468 except:
Victor Stinner367f5d32014-03-25 09:08:16 +0100469 _os.close(fd)
470 raise
Guido van Rossum0e548712002-08-09 16:14:33 +0000471
Jason Tishler80c02af2002-08-14 15:10:09 +0000472if _os.name != 'posix' or _os.sys.platform == 'cygwin':
473 # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
474 # while it is open.
Guido van Rossum0e548712002-08-09 16:14:33 +0000475 TemporaryFile = NamedTemporaryFile
Tim Peters1baa22a2001-01-12 10:02:46 +0000476
477else:
Guido van Rossum0e548712002-08-09 16:14:33 +0000478 def TemporaryFile(mode='w+b', bufsize=-1, suffix="",
Guido van Rossume888cdc2002-08-17 14:50:24 +0000479 prefix=template, dir=None):
Guido van Rossum0e548712002-08-09 16:14:33 +0000480 """Create and return a temporary file.
481 Arguments:
Neal Norwitz946aea22006-06-16 04:31:06 +0000482 'prefix', 'suffix', 'dir' -- as for mkstemp.
Guido van Rossum0e548712002-08-09 16:14:33 +0000483 'mode' -- the mode argument to os.fdopen (default "w+b").
484 'bufsize' -- the buffer size argument to os.fdopen (default -1).
485 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000486
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000487 Returns an object with a file-like interface. The file has no
488 name, and will cease to exist when it is closed.
Guido van Rossum0e548712002-08-09 16:14:33 +0000489 """
490
Guido van Rossume888cdc2002-08-17 14:50:24 +0000491 if dir is None:
492 dir = gettempdir()
493
Tim Petersc21ea742002-08-13 23:36:01 +0000494 if 'b' in mode:
495 flags = _bin_openflags
496 else:
497 flags = _text_openflags
Guido van Rossum0e548712002-08-09 16:14:33 +0000498
499 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
500 try:
501 _os.unlink(name)
502 return _os.fdopen(fd, mode, bufsize)
503 except:
504 _os.close(fd)
505 raise
Collin Wintera8785cc2007-03-19 18:52:08 +0000506
507class SpooledTemporaryFile:
508 """Temporary file wrapper, specialized to switch from
509 StringIO to a real file when it exceeds a certain size or
510 when a fileno is needed.
511 """
512 _rolled = False
513
514 def __init__(self, max_size=0, mode='w+b', bufsize=-1,
515 suffix="", prefix=template, dir=None):
516 self._file = _StringIO()
517 self._max_size = max_size
518 self._rolled = False
519 self._TemporaryFileArgs = (mode, bufsize, suffix, prefix, dir)
520
521 def _check(self, file):
522 if self._rolled: return
523 max_size = self._max_size
524 if max_size and file.tell() > max_size:
525 self.rollover()
526
527 def rollover(self):
528 if self._rolled: return
529 file = self._file
530 newfile = self._file = TemporaryFile(*self._TemporaryFileArgs)
531 del self._TemporaryFileArgs
532
533 newfile.write(file.getvalue())
534 newfile.seek(file.tell(), 0)
535
536 self._rolled = True
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000537
Nick Coghlan97fac3e2008-02-09 15:28:09 +0000538 # The method caching trick from NamedTemporaryFile
539 # won't work here, because _file may change from a
540 # _StringIO instance to a real file. So we list
541 # all the methods directly.
542
543 # Context management protocol
544 def __enter__(self):
545 if self._file.closed:
546 raise ValueError("Cannot enter context with closed file")
547 return self
548
549 def __exit__(self, exc, value, tb):
550 self._file.close()
551
Collin Wintera8785cc2007-03-19 18:52:08 +0000552 # file protocol
553 def __iter__(self):
554 return self._file.__iter__()
555
556 def close(self):
557 self._file.close()
558
559 @property
560 def closed(self):
561 return self._file.closed
562
Collin Wintera8785cc2007-03-19 18:52:08 +0000563 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 Storchakabeaa3ad2013-02-09 12:20:18 +0200575 try:
576 return self._file.mode
577 except AttributeError:
578 return self._TemporaryFileArgs[0]
Collin Wintera8785cc2007-03-19 18:52:08 +0000579
580 @property
581 def name(self):
Serhiy Storchakabeaa3ad2013-02-09 12:20:18 +0200582 try:
583 return self._file.name
584 except AttributeError:
585 return None
Collin Wintera8785cc2007-03-19 18:52:08 +0000586
587 def next(self):
588 return self._file.next
589
590 def read(self, *args):
591 return self._file.read(*args)
592
593 def readline(self, *args):
594 return self._file.readline(*args)
595
596 def readlines(self, *args):
597 return self._file.readlines(*args)
598
599 def seek(self, *args):
600 self._file.seek(*args)
601
602 @property
603 def softspace(self):
604 return self._file.softspace
605
606 def tell(self):
607 return self._file.tell()
608
609 def truncate(self):
610 self._file.truncate()
611
612 def write(self, s):
613 file = self._file
614 rv = file.write(s)
615 self._check(file)
616 return rv
617
618 def writelines(self, iterable):
619 file = self._file
620 rv = file.writelines(iterable)
621 self._check(file)
622 return rv
623
624 def xreadlines(self, *args):
Terry Jan Reedy6c1d9dd2013-06-30 13:57:57 -0400625 if hasattr(self._file, 'xreadlines'): # real file
626 return iter(self._file)
627 else: # StringIO()
Serhiy Storchakabeaa3ad2013-02-09 12:20:18 +0200628 return iter(self._file.readlines(*args))