3 This module provides generic, low- and high-level interfaces for
4 creating temporary files and directories. The interfaces listed
5 as "safe" just below can be used without fear of race conditions.
6 Those listed as "unsafe" cannot, and are provided for backward
9 This module also provides some data items to the user:
11 TMP_MAX - maximum number of names that will be tried before
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.
21 "NamedTemporaryFile", "TemporaryFile", # high level safe interfaces
22 "SpooledTemporaryFile",
23 "mkstemp", "mkdtemp", # low level safe interfaces
24 "mktemp", # deprecated unsafe interface
25 "TMP_MAX", "gettempprefix", # constants
26 "tempdir", "gettempdir"
33 import errno
as _errno
34 from random
import Random
as _Random
37 from cStringIO
import StringIO
as _StringIO
39 from StringIO
import StringIO
as _StringIO
42 import fcntl
as _fcntl
49 flags
= _fcntl
.fcntl(fd
, _fcntl
.F_GETFD
, 0)
53 # flags read successfully, modify
54 flags |
= _fcntl
.FD_CLOEXEC
55 _fcntl
.fcntl(fd
, _fcntl
.F_SETFD
, flags
)
59 import thread
as _thread
61 import dummy_thread
as _thread
62 _allocate_lock
= _thread
.allocate_lock
64 _text_openflags
= _os
.O_RDWR | _os
.O_CREAT | _os
.O_EXCL
65 if hasattr(_os
, 'O_NOINHERIT'):
66 _text_openflags |
= _os
.O_NOINHERIT
67 if hasattr(_os
, 'O_NOFOLLOW'):
68 _text_openflags |
= _os
.O_NOFOLLOW
70 _bin_openflags
= _text_openflags
71 if hasattr(_os
, 'O_BINARY'):
72 _bin_openflags |
= _os
.O_BINARY
74 if hasattr(_os
, 'TMP_MAX'):
83 _once_lock
= _allocate_lock()
85 if hasattr(_os
, "lstat"):
87 elif hasattr(_os
, "stat"):
90 # Fallback. All we need is something that raises os.error if the
107 class _RandomNameSequence
:
108 """An instance of _RandomNameSequence generates an endless
109 sequence of unpredictable strings which can safely be incorporated
110 into file names. Each string is six characters long. Multiple
111 threads can safely use the same instance at the same time.
113 _RandomNameSequence is an iterator."""
115 characters
= ("abcdefghijklmnopqrstuvwxyz" +
116 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
120 self
.mutex
= _allocate_lock()
122 self
.normcase
= _os
.path
.normcase
130 choose
= self
.rng
.choice
134 letters
= [choose(c
) for dummy
in "123456"]
138 return self
.normcase(''.join(letters
))
140 def _candidate_tempdir_list():
141 """Generate a list of candidate temporary directories which
142 _get_default_tempdir will try."""
146 # First, try the environment.
147 for envname
in 'TMPDIR', 'TEMP', 'TMP':
148 dirname
= _os
.getenv(envname
)
149 if dirname
: dirlist
.append(dirname
)
151 # Failing that, try OS-specific locations.
152 if _os
.name
== 'riscos':
153 dirname
= _os
.getenv('Wimp$ScrapDir')
154 if dirname
: dirlist
.append(dirname
)
155 elif _os
.name
== 'nt':
156 dirlist
.extend([ r
'c:\temp', r
'c:\tmp', r
'\temp', r
'\tmp' ])
158 dirlist
.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
160 # As a last resort, the current directory.
162 dirlist
.append(_os
.getcwd())
163 except (AttributeError, _os
.error
):
164 dirlist
.append(_os
.curdir
)
168 def _get_default_tempdir():
169 """Calculate the default directory to use for temporary files.
170 This routine should be called exactly once.
172 We determine whether or not a candidate temp dir is usable by
173 trying to create and write to a file in that directory. If this
174 is successful, the test file is deleted. To prevent denial of
175 service, the name of the test file must be randomized."""
177 namer
= _RandomNameSequence()
178 dirlist
= _candidate_tempdir_list()
179 flags
= _text_openflags
182 if dir != _os
.curdir
:
183 dir = _os
.path
.normcase(_os
.path
.abspath(dir))
184 # Try only a few names per directory.
185 for seq
in xrange(100):
187 filename
= _os
.path
.join(dir, name
)
189 fd
= _os
.open(filename
, flags
, 0600)
190 fp
= _os
.fdopen(fd
, 'w')
196 except (OSError, IOError), e
:
197 if e
[0] != _errno
.EEXIST
:
198 break # no point trying more names in this directory
200 raise IOError, (_errno
.ENOENT
,
201 ("No usable temporary directory found in %s" % dirlist
))
203 _name_sequence
= None
205 def _get_candidate_names():
206 """Common setup sequence for all user-callable interfaces."""
208 global _name_sequence
209 if _name_sequence
is None:
212 if _name_sequence
is None:
213 _name_sequence
= _RandomNameSequence()
216 return _name_sequence
219 def _mkstemp_inner(dir, pre
, suf
, flags
):
220 """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
222 names
= _get_candidate_names()
224 for seq
in xrange(TMP_MAX
):
226 file = _os
.path
.join(dir, pre
+ name
+ suf
)
228 fd
= _os
.open(file, flags
, 0600)
230 return (fd
, _os
.path
.abspath(file))
232 if e
.errno
== _errno
.EEXIST
:
236 raise IOError, (_errno
.EEXIST
, "No usable temporary file name found")
239 # User visible interfaces.
242 """Accessor for tempdir.template."""
248 """Accessor for tempfile.tempdir."""
254 tempdir
= _get_default_tempdir()
259 def mkstemp(suffix
="", prefix
=template
, dir=None, text
=False):
260 """User-callable function to create and return a unique temporary
261 file. The return value is a pair (fd, name) where fd is the
262 file descriptor returned by os.open, and name is the filename.
264 If 'suffix' is specified, the file name will end with that suffix,
265 otherwise there will be no suffix.
267 If 'prefix' is specified, the file name will begin with that prefix,
268 otherwise a default prefix is used.
270 If 'dir' is specified, the file will be created in that directory,
271 otherwise a default directory is used.
273 If 'text' is specified and true, the file is opened in text
274 mode. Else (the default) the file is opened in binary mode. On
275 some operating systems, this makes no difference.
277 The file is readable and writable only by the creating user ID.
278 If the operating system uses permission bits to indicate whether a
279 file is executable, the file is executable by no one. The file
280 descriptor is not inherited by children of this process.
282 Caller is responsible for deleting the file when done with it.
289 flags
= _text_openflags
291 flags
= _bin_openflags
293 return _mkstemp_inner(dir, prefix
, suffix
, flags
)
296 def mkdtemp(suffix
="", prefix
=template
, dir=None):
297 """User-callable function to create and return a unique temporary
298 directory. The return value is the pathname of the directory.
300 Arguments are as for mkstemp, except that the 'text' argument is
303 The directory is readable, writable, and searchable only by the
306 Caller is responsible for deleting the directory when done with it.
312 names
= _get_candidate_names()
314 for seq
in xrange(TMP_MAX
):
316 file = _os
.path
.join(dir, prefix
+ name
+ suffix
)
318 _os
.mkdir(file, 0700)
321 if e
.errno
== _errno
.EEXIST
:
325 raise IOError, (_errno
.EEXIST
, "No usable temporary directory name found")
327 def mktemp(suffix
="", prefix
=template
, dir=None):
328 """User-callable function to return a unique temporary file name. The
331 Arguments are as for mkstemp, except that the 'text' argument is
334 This function is unsafe and should not be used. The file name
335 refers to a file that did not exist at some point, but by the time
336 you get around to creating it, someone else may have beaten you to
340 ## from warnings import warn as _warn
341 ## _warn("mktemp is a potential security risk to your program",
342 ## RuntimeWarning, stacklevel=2)
347 names
= _get_candidate_names()
348 for seq
in xrange(TMP_MAX
):
350 file = _os
.path
.join(dir, prefix
+ name
+ suffix
)
351 if not _exists(file):
354 raise IOError, (_errno
.EEXIST
, "No usable temporary filename found")
357 class _TemporaryFileWrapper
:
358 """Temporary file wrapper
360 This class provides a wrapper around files opened for
361 temporary use. In particular, it seeks to automatically
362 remove the file when it is no longer needed.
365 def __init__(self
, file, name
, delete
=True):
368 self
.close_called
= False
371 def __getattr__(self
, name
):
372 # Attribute lookups are delegated to the underlying file
373 # and cached for non-numeric results
374 # (i.e. methods are cached, closed and friends are not)
375 file = self
.__dict
__['file']
376 a
= getattr(file, name
)
377 if not issubclass(type(a
), type(0)):
378 setattr(self
, name
, a
)
381 # The underlying __enter__ method returns the wrong object
382 # (self.file) so override it to return the wrapper
384 self
.file.__enter
__()
387 # NT provides delete-on-close as a primitive, so we don't need
388 # the wrapper to do anything special. We still use it so that
389 # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
391 # Cache the unlinker so we don't get spurious errors at
392 # shutdown when the module-level "os" is None'd out. Note
393 # that this must be referenced as self.unlink, because the
394 # name TemporaryFileWrapper may also get None'd out before
399 if not self
.close_called
:
400 self
.close_called
= True
403 self
.unlink(self
.name
)
408 # Need to trap __exit__ as well to ensure the file gets
409 # deleted when used in a with statement
410 def __exit__(self
, exc
, value
, tb
):
411 result
= self
.file.__exit
__(exc
, value
, tb
)
416 def NamedTemporaryFile(mode
='w+b', bufsize
=-1, suffix
="",
417 prefix
=template
, dir=None, delete
=True):
418 """Create and return a temporary file.
420 'prefix', 'suffix', 'dir' -- as for mkstemp.
421 'mode' -- the mode argument to os.fdopen (default "w+b").
422 'bufsize' -- the buffer size argument to os.fdopen (default -1).
423 'delete' -- whether the file is deleted on close (default True).
424 The file is created as mkstemp() would do it.
426 Returns an object with a file-like interface; the name of the file
427 is accessible as file.name. The file will be automatically deleted
428 when it is closed unless the 'delete' argument is set to False.
435 flags
= _bin_openflags
437 flags
= _text_openflags
439 # Setting O_TEMPORARY in the flags causes the OS to delete
440 # the file when it is closed. This is only supported by Windows.
441 if _os
.name
== 'nt' and delete
:
442 flags |
= _os
.O_TEMPORARY
444 (fd
, name
) = _mkstemp_inner(dir, prefix
, suffix
, flags
)
445 file = _os
.fdopen(fd
, mode
, bufsize
)
446 return _TemporaryFileWrapper(file, name
, delete
)
448 if _os
.name
!= 'posix' or _os
.sys
.platform
== 'cygwin':
449 # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
451 TemporaryFile
= NamedTemporaryFile
454 def TemporaryFile(mode
='w+b', bufsize
=-1, suffix
="",
455 prefix
=template
, dir=None):
456 """Create and return a temporary file.
458 'prefix', 'suffix', 'dir' -- as for mkstemp.
459 'mode' -- the mode argument to os.fdopen (default "w+b").
460 'bufsize' -- the buffer size argument to os.fdopen (default -1).
461 The file is created as mkstemp() would do it.
463 Returns an object with a file-like interface. The file has no
464 name, and will cease to exist when it is closed.
471 flags
= _bin_openflags
473 flags
= _text_openflags
475 (fd
, name
) = _mkstemp_inner(dir, prefix
, suffix
, flags
)
478 return _os
.fdopen(fd
, mode
, bufsize
)
483 class SpooledTemporaryFile
:
484 """Temporary file wrapper, specialized to switch from
485 StringIO to a real file when it exceeds a certain size or
486 when a fileno is needed.
490 def __init__(self
, max_size
=0, mode
='w+b', bufsize
=-1,
491 suffix
="", prefix
=template
, dir=None):
492 self
._file
= _StringIO()
493 self
._max
_size
= max_size
495 self
._TemporaryFileArgs
= (mode
, bufsize
, suffix
, prefix
, dir)
497 def _check(self
, file):
498 if self
._rolled
: return
499 max_size
= self
._max
_size
500 if max_size
and file.tell() > max_size
:
504 if self
._rolled
: return
506 newfile
= self
._file
= TemporaryFile(*self
._TemporaryFileArgs
)
507 del self
._TemporaryFileArgs
509 newfile
.write(file.getvalue())
510 newfile
.seek(file.tell(), 0)
514 # The method caching trick from NamedTemporaryFile
515 # won't work here, because _file may change from a
516 # _StringIO instance to a real file. So we list
517 # all the methods directly.
519 # Context management protocol
521 if self
._file
.closed
:
522 raise ValueError("Cannot enter context with closed file")
525 def __exit__(self
, exc
, value
, tb
):
530 return self
._file
.__iter
__()
537 return self
._file
.closed
541 return self
._file
.encoding
545 return self
._file
.fileno()
551 return self
._file
.isatty()
555 return self
._file
.mode
559 return self
._file
.name
563 return self
._file
.newlines
566 return self
._file
.next
568 def read(self
, *args
):
569 return self
._file
.read(*args
)
571 def readline(self
, *args
):
572 return self
._file
.readline(*args
)
574 def readlines(self
, *args
):
575 return self
._file
.readlines(*args
)
577 def seek(self
, *args
):
578 self
._file
.seek(*args
)
582 return self
._file
.softspace
585 return self
._file
.tell()
588 self
._file
.truncate()
596 def writelines(self
, iterable
):
598 rv
= file.writelines(iterable
)
602 def xreadlines(self
, *args
):
603 return self
._file
.xreadlines(*args
)