blob: e75c8fec8a8a5a1bd1dea3468e23924f59fd476f [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
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
Guido van Rossum0e548712002-08-09 16:14:33 +000032import os as _os
33import errno as _errno
34from random import Random as _Random
35
36if _os.name == 'mac':
Jack Jansenbb829b72003-03-21 12:55:38 +000037 import Carbon.Folder as _Folder
38 import Carbon.Folders as _Folders
Guido van Rossum0e548712002-08-09 16:14:33 +000039
40try:
Neal Norwitz0d4c06e2007-04-25 06:30:05 +000041 from cStringIO import StringIO as _StringIO
Collin Wintera8785cc2007-03-19 18:52:08 +000042except:
Neal Norwitz0d4c06e2007-04-25 06:30:05 +000043 from StringIO import StringIO as _StringIO
Collin Wintera8785cc2007-03-19 18:52:08 +000044
45try:
Guido van Rossum0e548712002-08-09 16:14:33 +000046 import fcntl as _fcntl
Tim Peters90ee7eb2004-07-18 23:58:17 +000047except ImportError:
Tim Peters291f14e2003-07-22 02:50:01 +000048 def _set_cloexec(fd):
49 pass
50else:
Guido van Rossum0e548712002-08-09 16:14:33 +000051 def _set_cloexec(fd):
Tim Peters90ee7eb2004-07-18 23:58:17 +000052 try:
53 flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0)
54 except IOError:
55 pass
Alex Martellif09994e2003-11-09 16:44:09 +000056 else:
Guido van Rossum0e548712002-08-09 16:14:33 +000057 # flags read successfully, modify
58 flags |= _fcntl.FD_CLOEXEC
59 _fcntl.fcntl(fd, _fcntl.F_SETFD, flags)
Tim Peters291f14e2003-07-22 02:50:01 +000060
Guido van Rossum0e548712002-08-09 16:14:33 +000061
62try:
63 import thread as _thread
Guido van Rossuma0934242002-12-30 22:36:09 +000064except ImportError:
65 import dummy_thread as _thread
66_allocate_lock = _thread.allocate_lock
Guido van Rossum0e548712002-08-09 16:14:33 +000067
68_text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL
Tim Petersa0d55de2002-08-09 18:01:01 +000069if hasattr(_os, 'O_NOINHERIT'):
70 _text_openflags |= _os.O_NOINHERIT
71if hasattr(_os, 'O_NOFOLLOW'):
72 _text_openflags |= _os.O_NOFOLLOW
Guido van Rossum0e548712002-08-09 16:14:33 +000073
74_bin_openflags = _text_openflags
Tim Petersa0d55de2002-08-09 18:01:01 +000075if hasattr(_os, 'O_BINARY'):
76 _bin_openflags |= _os.O_BINARY
Guido van Rossum0e548712002-08-09 16:14:33 +000077
78if hasattr(_os, 'TMP_MAX'):
79 TMP_MAX = _os.TMP_MAX
80else:
81 TMP_MAX = 10000
82
Tim Petersbd7b4c72002-08-13 23:33:56 +000083template = "tmp"
Guido van Rossum0e548712002-08-09 16:14:33 +000084
85tempdir = None
86
87# Internal routines.
88
89_once_lock = _allocate_lock()
90
Guido van Rossumb256159392003-11-10 02:16:36 +000091if hasattr(_os, "lstat"):
92 _stat = _os.lstat
93elif hasattr(_os, "stat"):
94 _stat = _os.stat
95else:
96 # Fallback. All we need is something that raises os.error if the
97 # file doesn't exist.
98 def _stat(fn):
99 try:
100 f = open(fn)
101 except IOError:
102 raise _os.error
103 f.close()
104
105def _exists(fn):
106 try:
107 _stat(fn)
108 except _os.error:
109 return False
110 else:
111 return True
112
Guido van Rossum0e548712002-08-09 16:14:33 +0000113class _RandomNameSequence:
114 """An instance of _RandomNameSequence generates an endless
115 sequence of unpredictable strings which can safely be incorporated
116 into file names. Each string is six characters long. Multiple
117 threads can safely use the same instance at the same time.
118
119 _RandomNameSequence is an iterator."""
120
Tim Peters97701b52002-11-21 15:59:59 +0000121 characters = ("abcdefghijklmnopqrstuvwxyz" +
122 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
Collin Winter9b2a1092007-03-08 22:16:25 +0000123 "0123456789_")
Guido van Rossum0e548712002-08-09 16:14:33 +0000124
125 def __init__(self):
126 self.mutex = _allocate_lock()
127 self.rng = _Random()
128 self.normcase = _os.path.normcase
Tim Peters97701b52002-11-21 15:59:59 +0000129
Guido van Rossum0e548712002-08-09 16:14:33 +0000130 def __iter__(self):
131 return self
132
133 def next(self):
134 m = self.mutex
135 c = self.characters
Tim Peters97701b52002-11-21 15:59:59 +0000136 choose = self.rng.choice
Guido van Rossum0e548712002-08-09 16:14:33 +0000137
Tim Peters97701b52002-11-21 15:59:59 +0000138 m.acquire()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000139 try:
Tim Peters97701b52002-11-21 15:59:59 +0000140 letters = [choose(c) for dummy in "123456"]
Guido van Rossum0e548712002-08-09 16:14:33 +0000141 finally:
142 m.release()
143
Tim Peters97701b52002-11-21 15:59:59 +0000144 return self.normcase(''.join(letters))
Guido van Rossum0e548712002-08-09 16:14:33 +0000145
146def _candidate_tempdir_list():
147 """Generate a list of candidate temporary directories which
148 _get_default_tempdir will try."""
149
150 dirlist = []
151
152 # First, try the environment.
153 for envname in 'TMPDIR', 'TEMP', 'TMP':
154 dirname = _os.getenv(envname)
155 if dirname: dirlist.append(dirname)
156
157 # Failing that, try OS-specific locations.
158 if _os.name == 'mac':
159 try:
Jack Jansenbb829b72003-03-21 12:55:38 +0000160 fsr = _Folder.FSFindFolder(_Folders.kOnSystemDisk,
161 _Folders.kTemporaryFolderType, 1)
162 dirname = fsr.as_pathname()
Guido van Rossum0e548712002-08-09 16:14:33 +0000163 dirlist.append(dirname)
Jack Jansenbb829b72003-03-21 12:55:38 +0000164 except _Folder.error:
Guido van Rossum0e548712002-08-09 16:14:33 +0000165 pass
166 elif _os.name == 'riscos':
167 dirname = _os.getenv('Wimp$ScrapDir')
168 if dirname: dirlist.append(dirname)
169 elif _os.name == 'nt':
170 dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
171 else:
172 dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
173
174 # As a last resort, the current directory.
175 try:
176 dirlist.append(_os.getcwd())
177 except (AttributeError, _os.error):
178 dirlist.append(_os.curdir)
179
180 return dirlist
Tim Petersa0d55de2002-08-09 18:01:01 +0000181
Guido van Rossum0e548712002-08-09 16:14:33 +0000182def _get_default_tempdir():
183 """Calculate the default directory to use for temporary files.
Guido van Rossume888cdc2002-08-17 14:50:24 +0000184 This routine should be called exactly once.
Guido van Rossum0e548712002-08-09 16:14:33 +0000185
186 We determine whether or not a candidate temp dir is usable by
187 trying to create and write to a file in that directory. If this
188 is successful, the test file is deleted. To prevent denial of
189 service, the name of the test file must be randomized."""
190
191 namer = _RandomNameSequence()
192 dirlist = _candidate_tempdir_list()
193 flags = _text_openflags
194
195 for dir in dirlist:
196 if dir != _os.curdir:
197 dir = _os.path.normcase(_os.path.abspath(dir))
198 # Try only a few names per directory.
199 for seq in xrange(100):
200 name = namer.next()
201 filename = _os.path.join(dir, name)
202 try:
203 fd = _os.open(filename, flags, 0600)
204 fp = _os.fdopen(fd, 'w')
Tim Petersb90f89a2001-01-15 03:26:36 +0000205 fp.write('blat')
206 fp.close()
Guido van Rossum0e548712002-08-09 16:14:33 +0000207 _os.unlink(filename)
208 del fp, fd
209 return dir
210 except (OSError, IOError), e:
211 if e[0] != _errno.EEXIST:
212 break # no point trying more names in this directory
213 pass
214 raise IOError, (_errno.ENOENT,
215 ("No usable temporary directory found in %s" % dirlist))
216
Guido van Rossume888cdc2002-08-17 14:50:24 +0000217_name_sequence = None
218
Guido van Rossum0e548712002-08-09 16:14:33 +0000219def _get_candidate_names():
220 """Common setup sequence for all user-callable interfaces."""
221
Guido van Rossume888cdc2002-08-17 14:50:24 +0000222 global _name_sequence
223 if _name_sequence is None:
224 _once_lock.acquire()
225 try:
226 if _name_sequence is None:
227 _name_sequence = _RandomNameSequence()
228 finally:
229 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000230 return _name_sequence
Guido van Rossum41f95031992-03-31 19:02:01 +0000231
232
Guido van Rossum0e548712002-08-09 16:14:33 +0000233def _mkstemp_inner(dir, pre, suf, flags):
234 """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
Tim Peters9fadfb02001-01-13 03:04:02 +0000235
Guido van Rossum0e548712002-08-09 16:14:33 +0000236 names = _get_candidate_names()
237
238 for seq in xrange(TMP_MAX):
239 name = names.next()
240 file = _os.path.join(dir, pre + name + suf)
241 try:
242 fd = _os.open(file, flags, 0600)
243 _set_cloexec(fd)
Martin v. Löwisd6625482003-10-12 17:37:01 +0000244 return (fd, _os.path.abspath(file))
Guido van Rossum0e548712002-08-09 16:14:33 +0000245 except OSError, e:
246 if e.errno == _errno.EEXIST:
247 continue # try again
248 raise
249
250 raise IOError, (_errno.EEXIST, "No usable temporary file name found")
Tim Petersa0d55de2002-08-09 18:01:01 +0000251
Guido van Rossum0e548712002-08-09 16:14:33 +0000252
253# User visible interfaces.
Guido van Rossumb0e57181998-10-14 20:27:05 +0000254
Guido van Rossum41f95031992-03-31 19:02:01 +0000255def gettempprefix():
Guido van Rossum0e548712002-08-09 16:14:33 +0000256 """Accessor for tempdir.template."""
257 return template
Tim Peters9fadfb02001-01-13 03:04:02 +0000258
Guido van Rossume888cdc2002-08-17 14:50:24 +0000259tempdir = None
260
Guido van Rossum0e548712002-08-09 16:14:33 +0000261def gettempdir():
262 """Accessor for tempdir.tempdir."""
Guido van Rossume888cdc2002-08-17 14:50:24 +0000263 global tempdir
264 if tempdir is None:
265 _once_lock.acquire()
266 try:
267 if tempdir is None:
268 tempdir = _get_default_tempdir()
269 finally:
270 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000271 return tempdir
272
Guido van Rossume888cdc2002-08-17 14:50:24 +0000273def mkstemp(suffix="", prefix=template, dir=None, text=False):
Tim Peters04490bf2002-08-14 15:41:26 +0000274 """mkstemp([suffix, [prefix, [dir, [text]]]])
Guido van Rossum0e548712002-08-09 16:14:33 +0000275 User-callable function to create and return a unique temporary
276 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):
Guido van Rossum0e548712002-08-09 16:14:33 +0000312 """mkdtemp([suffix, [prefix, [dir]]])
313 User-callable function to create and return a unique temporary
314 directory. The return value is the pathname of the directory.
315
Tim Peters04490bf2002-08-14 15:41:26 +0000316 Arguments are as for mkstemp, except that the 'text' argument is
Guido van Rossum0e548712002-08-09 16:14:33 +0000317 not accepted.
318
319 The directory is readable, writable, and searchable only by the
320 creating user.
321
322 Caller is responsible for deleting the directory when done with it.
323 """
324
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()
Tim Petersa0d55de2002-08-09 18:01:01 +0000329
Guido van Rossum0e548712002-08-09 16:14:33 +0000330 for seq in xrange(TMP_MAX):
331 name = names.next()
332 file = _os.path.join(dir, prefix + name + suffix)
333 try:
334 _os.mkdir(file, 0700)
335 return file
336 except OSError, e:
337 if e.errno == _errno.EEXIST:
338 continue # try again
339 raise
340
341 raise IOError, (_errno.EEXIST, "No usable temporary directory name found")
342
Guido van Rossume888cdc2002-08-17 14:50:24 +0000343def mktemp(suffix="", prefix=template, dir=None):
Guido van Rossum0e548712002-08-09 16:14:33 +0000344 """mktemp([suffix, [prefix, [dir]]])
345 User-callable function to return a unique temporary file name. The
346 file is not created.
347
Tim Peters04490bf2002-08-14 15:41:26 +0000348 Arguments are as for mkstemp, except that the 'text' argument is
Guido van Rossum0e548712002-08-09 16:14:33 +0000349 not accepted.
350
351 This function is unsafe and should not be used. The file name
352 refers to a file that did not exist at some point, but by the time
353 you get around to creating it, someone else may have beaten you to
354 the punch.
355 """
356
Guido van Rossum44f602d2002-11-22 15:56:29 +0000357## from warnings import warn as _warn
358## _warn("mktemp is a potential security risk to your program",
359## RuntimeWarning, stacklevel=2)
Guido van Rossum0e548712002-08-09 16:14:33 +0000360
Guido van Rossume888cdc2002-08-17 14:50:24 +0000361 if dir is None:
362 dir = gettempdir()
363
Guido van Rossum0e548712002-08-09 16:14:33 +0000364 names = _get_candidate_names()
365 for seq in xrange(TMP_MAX):
366 name = names.next()
367 file = _os.path.join(dir, prefix + name + suffix)
Guido van Rossumb256159392003-11-10 02:16:36 +0000368 if not _exists(file):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000369 return file
Guido van Rossumca549821997-08-12 18:00:12 +0000370
Guido van Rossum0e548712002-08-09 16:14:33 +0000371 raise IOError, (_errno.EEXIST, "No usable temporary filename found")
Guido van Rossumca549821997-08-12 18:00:12 +0000372
Nick Coghlan97fac3e2008-02-09 15:28:09 +0000373
Guido van Rossum0e548712002-08-09 16:14:33 +0000374class _TemporaryFileWrapper:
Guido van Rossumca549821997-08-12 18:00:12 +0000375 """Temporary file wrapper
376
Guido van Rossum0e548712002-08-09 16:14:33 +0000377 This class provides a wrapper around files opened for
378 temporary use. In particular, it seeks to automatically
379 remove the file when it is no longer needed.
Guido van Rossumca549821997-08-12 18:00:12 +0000380 """
Tim Petersa255a722001-12-18 22:32:40 +0000381
Georg Brandl35ef9c12007-03-13 18:31:49 +0000382 def __init__(self, file, name, delete=True):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000383 self.file = file
Guido van Rossum0e548712002-08-09 16:14:33 +0000384 self.name = name
Tim Peters6ef966e2002-11-21 15:48:33 +0000385 self.close_called = False
Georg Brandl35ef9c12007-03-13 18:31:49 +0000386 self.delete = delete
Guido van Rossumca549821997-08-12 18:00:12 +0000387
Guido van Rossumca549821997-08-12 18:00:12 +0000388 def __getattr__(self, name):
Nick Coghlan97fac3e2008-02-09 15:28:09 +0000389 # Attribute lookups are delegated to the underlying file
390 # and cached for non-numeric results
391 # (i.e. methods are cached, closed and friends are not)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000392 file = self.__dict__['file']
393 a = getattr(file, name)
Nick Coghlan97fac3e2008-02-09 15:28:09 +0000394 if not issubclass(type(a), type(0)):
Guido van Rossum6b708d51999-06-01 18:55:36 +0000395 setattr(self, name, a)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000396 return a
Guido van Rossumca549821997-08-12 18:00:12 +0000397
Nick Coghlan97fac3e2008-02-09 15:28:09 +0000398 # The underlying __enter__ method returns the wrong object
399 # (self.file) so override it to return the wrapper
400 def __enter__(self):
401 self.file.__enter__()
402 return self
403
Guido van Rossum0e548712002-08-09 16:14:33 +0000404 # NT provides delete-on-close as a primitive, so we don't need
405 # the wrapper to do anything special. We still use it so that
406 # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
407 if _os.name != 'nt':
Guido van Rossum0e548712002-08-09 16:14:33 +0000408 # Cache the unlinker so we don't get spurious errors at
409 # shutdown when the module-level "os" is None'd out. Note
410 # that this must be referenced as self.unlink, because the
411 # name TemporaryFileWrapper may also get None'd out before
412 # __del__ is called.
413 unlink = _os.unlink
Tim Peters1baa22a2001-01-12 10:02:46 +0000414
Guido van Rossum0e548712002-08-09 16:14:33 +0000415 def close(self):
416 if not self.close_called:
Tim Peters6ef966e2002-11-21 15:48:33 +0000417 self.close_called = True
Guido van Rossum0e548712002-08-09 16:14:33 +0000418 self.file.close()
Georg Brandl35ef9c12007-03-13 18:31:49 +0000419 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
431
432
Guido van Rossum0e548712002-08-09 16:14:33 +0000433def NamedTemporaryFile(mode='w+b', bufsize=-1, suffix="",
Georg Brandl35ef9c12007-03-13 18:31:49 +0000434 prefix=template, dir=None, delete=True):
Guido van Rossum0e548712002-08-09 16:14:33 +0000435 """Create and return a temporary file.
436 Arguments:
437 'prefix', 'suffix', 'dir' -- as for mkstemp.
438 'mode' -- the mode argument to os.fdopen (default "w+b").
439 'bufsize' -- the buffer size argument to os.fdopen (default -1).
Georg Brandl35ef9c12007-03-13 18:31:49 +0000440 'delete' -- whether the file is deleted on close (default True).
Guido van Rossum0e548712002-08-09 16:14:33 +0000441 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000442
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000443 Returns an object with a file-like interface; the name of the file
444 is accessible as file.name. The file will be automatically deleted
Georg Brandl35ef9c12007-03-13 18:31:49 +0000445 when it is closed unless the 'delete' argument is set to False.
Guido van Rossum0e548712002-08-09 16:14:33 +0000446 """
Tim Peters1baa22a2001-01-12 10:02:46 +0000447
Guido van Rossume888cdc2002-08-17 14:50:24 +0000448 if dir is None:
449 dir = gettempdir()
450
Tim Petersc21ea742002-08-13 23:36:01 +0000451 if 'b' in mode:
452 flags = _bin_openflags
453 else:
454 flags = _text_openflags
Tim Peters1baa22a2001-01-12 10:02:46 +0000455
Guido van Rossum0e548712002-08-09 16:14:33 +0000456 # Setting O_TEMPORARY in the flags causes the OS to delete
457 # the file when it is closed. This is only supported by Windows.
Georg Brandl35ef9c12007-03-13 18:31:49 +0000458 if _os.name == 'nt' and delete:
Guido van Rossum0e548712002-08-09 16:14:33 +0000459 flags |= _os.O_TEMPORARY
Tim Peters1baa22a2001-01-12 10:02:46 +0000460
Guido van Rossum0e548712002-08-09 16:14:33 +0000461 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
462 file = _os.fdopen(fd, mode, bufsize)
Georg Brandl35ef9c12007-03-13 18:31:49 +0000463 return _TemporaryFileWrapper(file, name, delete)
Guido van Rossum0e548712002-08-09 16:14:33 +0000464
Jason Tishler80c02af2002-08-14 15:10:09 +0000465if _os.name != 'posix' or _os.sys.platform == 'cygwin':
466 # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
467 # while it is open.
Guido van Rossum0e548712002-08-09 16:14:33 +0000468 TemporaryFile = NamedTemporaryFile
Tim Peters1baa22a2001-01-12 10:02:46 +0000469
470else:
Guido van Rossum0e548712002-08-09 16:14:33 +0000471 def TemporaryFile(mode='w+b', bufsize=-1, suffix="",
Guido van Rossume888cdc2002-08-17 14:50:24 +0000472 prefix=template, dir=None):
Guido van Rossum0e548712002-08-09 16:14:33 +0000473 """Create and return a temporary file.
474 Arguments:
Neal Norwitz946aea22006-06-16 04:31:06 +0000475 'prefix', 'suffix', 'dir' -- as for mkstemp.
Guido van Rossum0e548712002-08-09 16:14:33 +0000476 'mode' -- the mode argument to os.fdopen (default "w+b").
477 'bufsize' -- the buffer size argument to os.fdopen (default -1).
478 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000479
Raymond Hettingerfaa10eb2005-01-11 15:33:03 +0000480 Returns an object with a file-like interface. The file has no
481 name, and will cease to exist when it is closed.
Guido van Rossum0e548712002-08-09 16:14:33 +0000482 """
483
Guido van Rossume888cdc2002-08-17 14:50:24 +0000484 if dir is None:
485 dir = gettempdir()
486
Tim Petersc21ea742002-08-13 23:36:01 +0000487 if 'b' in mode:
488 flags = _bin_openflags
489 else:
490 flags = _text_openflags
Guido van Rossum0e548712002-08-09 16:14:33 +0000491
492 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
493 try:
494 _os.unlink(name)
495 return _os.fdopen(fd, mode, bufsize)
496 except:
497 _os.close(fd)
498 raise
Collin Wintera8785cc2007-03-19 18:52:08 +0000499
500class SpooledTemporaryFile:
501 """Temporary file wrapper, specialized to switch from
502 StringIO to a real file when it exceeds a certain size or
503 when a fileno is needed.
504 """
505 _rolled = False
506
507 def __init__(self, max_size=0, mode='w+b', bufsize=-1,
508 suffix="", prefix=template, dir=None):
509 self._file = _StringIO()
510 self._max_size = max_size
511 self._rolled = False
512 self._TemporaryFileArgs = (mode, bufsize, suffix, prefix, dir)
513
514 def _check(self, file):
515 if self._rolled: return
516 max_size = self._max_size
517 if max_size and file.tell() > max_size:
518 self.rollover()
519
520 def rollover(self):
521 if self._rolled: return
522 file = self._file
523 newfile = self._file = TemporaryFile(*self._TemporaryFileArgs)
524 del self._TemporaryFileArgs
525
526 newfile.write(file.getvalue())
527 newfile.seek(file.tell(), 0)
528
529 self._rolled = True
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000530
Nick Coghlan97fac3e2008-02-09 15:28:09 +0000531 # The method caching trick from NamedTemporaryFile
532 # won't work here, because _file may change from a
533 # _StringIO instance to a real file. So we list
534 # all the methods directly.
535
536 # Context management protocol
537 def __enter__(self):
538 if self._file.closed:
539 raise ValueError("Cannot enter context with closed file")
540 return self
541
542 def __exit__(self, exc, value, tb):
543 self._file.close()
544
Collin Wintera8785cc2007-03-19 18:52:08 +0000545 # file protocol
546 def __iter__(self):
547 return self._file.__iter__()
548
549 def close(self):
550 self._file.close()
551
552 @property
553 def closed(self):
554 return self._file.closed
555
556 @property
557 def encoding(self):
558 return self._file.encoding
559
560 def fileno(self):
561 self.rollover()
562 return self._file.fileno()
563
564 def flush(self):
565 self._file.flush()
566
567 def isatty(self):
568 return self._file.isatty()
569
570 @property
571 def mode(self):
572 return self._file.mode
573
574 @property
575 def name(self):
576 return self._file.name
577
578 @property
579 def newlines(self):
580 return self._file.newlines
581
582 def next(self):
583 return self._file.next
584
585 def read(self, *args):
586 return self._file.read(*args)
587
588 def readline(self, *args):
589 return self._file.readline(*args)
590
591 def readlines(self, *args):
592 return self._file.readlines(*args)
593
594 def seek(self, *args):
595 self._file.seek(*args)
596
597 @property
598 def softspace(self):
599 return self._file.softspace
600
601 def tell(self):
602 return self._file.tell()
603
604 def truncate(self):
605 self._file.truncate()
606
607 def write(self, s):
608 file = self._file
609 rv = file.write(s)
610 self._check(file)
611 return rv
612
613 def writelines(self, iterable):
614 file = self._file
615 rv = file.writelines(iterable)
616 self._check(file)
617 return rv
618
619 def xreadlines(self, *args):
620 return self._file.xreadlines(*args)