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 import Carbon
.Folder
as _Folder
38 import Carbon
.Folders
as _Folders
41 from cStringIO
import StringIO
as _StringIO
43 from StringIO
import StringIO
as _StringIO
46 import fcntl
as _fcntl
53 flags
= _fcntl
.fcntl(fd
, _fcntl
.F_GETFD
, 0)
57 # flags read successfully, modify
58 flags |
= _fcntl
.FD_CLOEXEC
59 _fcntl
.fcntl(fd
, _fcntl
.F_SETFD
, flags
)
63 import thread
as _thread
65 import dummy_thread
as _thread
66 _allocate_lock
= _thread
.allocate_lock
68 _text_openflags
= _os
.O_RDWR | _os
.O_CREAT | _os
.O_EXCL
69 if hasattr(_os
, 'O_NOINHERIT'):
70 _text_openflags |
= _os
.O_NOINHERIT
71 if hasattr(_os
, 'O_NOFOLLOW'):
72 _text_openflags |
= _os
.O_NOFOLLOW
74 _bin_openflags
= _text_openflags
75 if hasattr(_os
, 'O_BINARY'):
76 _bin_openflags |
= _os
.O_BINARY
78 if hasattr(_os
, 'TMP_MAX'):
87 _once_lock
= _allocate_lock()
89 if hasattr(_os
, "lstat"):
91 elif hasattr(_os
, "stat"):
94 # Fallback. All we need is something that raises os.error if the
111 class _RandomNameSequence
:
112 """An instance of _RandomNameSequence generates an endless
113 sequence of unpredictable strings which can safely be incorporated
114 into file names. Each string is six characters long. Multiple
115 threads can safely use the same instance at the same time.
117 _RandomNameSequence is an iterator."""
119 characters
= ("abcdefghijklmnopqrstuvwxyz" +
120 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
124 self
.mutex
= _allocate_lock()
126 self
.normcase
= _os
.path
.normcase
134 choose
= self
.rng
.choice
138 letters
= [choose(c
) for dummy
in "123456"]
142 return self
.normcase(''.join(letters
))
144 def _candidate_tempdir_list():
145 """Generate a list of candidate temporary directories which
146 _get_default_tempdir will try."""
150 # First, try the environment.
151 for envname
in 'TMPDIR', 'TEMP', 'TMP':
152 dirname
= _os
.getenv(envname
)
153 if dirname
: dirlist
.append(dirname
)
155 # Failing that, try OS-specific locations.
156 if _os
.name
== 'mac':
158 fsr
= _Folder
.FSFindFolder(_Folders
.kOnSystemDisk
,
159 _Folders
.kTemporaryFolderType
, 1)
160 dirname
= fsr
.as_pathname()
161 dirlist
.append(dirname
)
162 except _Folder
.error
:
164 elif _os
.name
== 'riscos':
165 dirname
= _os
.getenv('Wimp$ScrapDir')
166 if dirname
: dirlist
.append(dirname
)
167 elif _os
.name
== 'nt':
168 dirlist
.extend([ r
'c:\temp', r
'c:\tmp', r
'\temp', r
'\tmp' ])
170 dirlist
.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
172 # As a last resort, the current directory.
174 dirlist
.append(_os
.getcwd())
175 except (AttributeError, _os
.error
):
176 dirlist
.append(_os
.curdir
)
180 def _get_default_tempdir():
181 """Calculate the default directory to use for temporary files.
182 This routine should be called exactly once.
184 We determine whether or not a candidate temp dir is usable by
185 trying to create and write to a file in that directory. If this
186 is successful, the test file is deleted. To prevent denial of
187 service, the name of the test file must be randomized."""
189 namer
= _RandomNameSequence()
190 dirlist
= _candidate_tempdir_list()
191 flags
= _text_openflags
194 if dir != _os
.curdir
:
195 dir = _os
.path
.normcase(_os
.path
.abspath(dir))
196 # Try only a few names per directory.
197 for seq
in xrange(100):
199 filename
= _os
.path
.join(dir, name
)
201 fd
= _os
.open(filename
, flags
, 0600)
202 fp
= _os
.fdopen(fd
, 'w')
208 except (OSError, IOError), e
:
209 if e
[0] != _errno
.EEXIST
:
210 break # no point trying more names in this directory
212 raise IOError, (_errno
.ENOENT
,
213 ("No usable temporary directory found in %s" % dirlist
))
215 _name_sequence
= None
217 def _get_candidate_names():
218 """Common setup sequence for all user-callable interfaces."""
220 global _name_sequence
221 if _name_sequence
is None:
224 if _name_sequence
is None:
225 _name_sequence
= _RandomNameSequence()
228 return _name_sequence
231 def _mkstemp_inner(dir, pre
, suf
, flags
):
232 """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
234 names
= _get_candidate_names()
236 for seq
in xrange(TMP_MAX
):
238 file = _os
.path
.join(dir, pre
+ name
+ suf
)
240 fd
= _os
.open(file, flags
, 0600)
242 return (fd
, _os
.path
.abspath(file))
244 if e
.errno
== _errno
.EEXIST
:
248 raise IOError, (_errno
.EEXIST
, "No usable temporary file name found")
251 # User visible interfaces.
254 """Accessor for tempdir.template."""
260 """Accessor for tempfile.tempdir."""
266 tempdir
= _get_default_tempdir()
271 def mkstemp(suffix
="", prefix
=template
, dir=None, text
=False):
272 """User-callable function to create and return a unique temporary
273 file. The return value is a pair (fd, name) where fd is the
274 file descriptor returned by os.open, and name is the filename.
276 If 'suffix' is specified, the file name will end with that suffix,
277 otherwise there will be no suffix.
279 If 'prefix' is specified, the file name will begin with that prefix,
280 otherwise a default prefix is used.
282 If 'dir' is specified, the file will be created in that directory,
283 otherwise a default directory is used.
285 If 'text' is specified and true, the file is opened in text
286 mode. Else (the default) the file is opened in binary mode. On
287 some operating systems, this makes no difference.
289 The file is readable and writable only by the creating user ID.
290 If the operating system uses permission bits to indicate whether a
291 file is executable, the file is executable by no one. The file
292 descriptor is not inherited by children of this process.
294 Caller is responsible for deleting the file when done with it.
301 flags
= _text_openflags
303 flags
= _bin_openflags
305 return _mkstemp_inner(dir, prefix
, suffix
, flags
)
308 def mkdtemp(suffix
="", prefix
=template
, dir=None):
309 """User-callable function to create and return a unique temporary
310 directory. The return value is the pathname of the directory.
312 Arguments are as for mkstemp, except that the 'text' argument is
315 The directory is readable, writable, and searchable only by the
318 Caller is responsible for deleting the directory when done with it.
324 names
= _get_candidate_names()
326 for seq
in xrange(TMP_MAX
):
328 file = _os
.path
.join(dir, prefix
+ name
+ suffix
)
330 _os
.mkdir(file, 0700)
333 if e
.errno
== _errno
.EEXIST
:
337 raise IOError, (_errno
.EEXIST
, "No usable temporary directory name found")
339 def mktemp(suffix
="", prefix
=template
, dir=None):
340 """User-callable function to return a unique temporary file name. The
343 Arguments are as for mkstemp, except that the 'text' argument is
346 This function is unsafe and should not be used. The file name
347 refers to a file that did not exist at some point, but by the time
348 you get around to creating it, someone else may have beaten you to
352 ## from warnings import warn as _warn
353 ## _warn("mktemp is a potential security risk to your program",
354 ## RuntimeWarning, stacklevel=2)
359 names
= _get_candidate_names()
360 for seq
in xrange(TMP_MAX
):
362 file = _os
.path
.join(dir, prefix
+ name
+ suffix
)
363 if not _exists(file):
366 raise IOError, (_errno
.EEXIST
, "No usable temporary filename found")
369 class _TemporaryFileWrapper
:
370 """Temporary file wrapper
372 This class provides a wrapper around files opened for
373 temporary use. In particular, it seeks to automatically
374 remove the file when it is no longer needed.
377 def __init__(self
, file, name
, delete
=True):
380 self
.close_called
= False
383 def __getattr__(self
, name
):
384 # Attribute lookups are delegated to the underlying file
385 # and cached for non-numeric results
386 # (i.e. methods are cached, closed and friends are not)
387 file = self
.__dict
__['file']
388 a
= getattr(file, name
)
389 if not issubclass(type(a
), type(0)):
390 setattr(self
, name
, a
)
393 # The underlying __enter__ method returns the wrong object
394 # (self.file) so override it to return the wrapper
396 self
.file.__enter
__()
399 # NT provides delete-on-close as a primitive, so we don't need
400 # the wrapper to do anything special. We still use it so that
401 # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
403 # Cache the unlinker so we don't get spurious errors at
404 # shutdown when the module-level "os" is None'd out. Note
405 # that this must be referenced as self.unlink, because the
406 # name TemporaryFileWrapper may also get None'd out before
411 if not self
.close_called
:
412 self
.close_called
= True
415 self
.unlink(self
.name
)
420 # Need to trap __exit__ as well to ensure the file gets
421 # deleted when used in a with statement
422 def __exit__(self
, exc
, value
, tb
):
423 result
= self
.file.__exit
__(exc
, value
, tb
)
428 def NamedTemporaryFile(mode
='w+b', bufsize
=-1, suffix
="",
429 prefix
=template
, dir=None, delete
=True):
430 """Create and return a temporary file.
432 'prefix', 'suffix', 'dir' -- as for mkstemp.
433 'mode' -- the mode argument to os.fdopen (default "w+b").
434 'bufsize' -- the buffer size argument to os.fdopen (default -1).
435 'delete' -- whether the file is deleted on close (default True).
436 The file is created as mkstemp() would do it.
438 Returns an object with a file-like interface; the name of the file
439 is accessible as file.name. The file will be automatically deleted
440 when it is closed unless the 'delete' argument is set to False.
447 flags
= _bin_openflags
449 flags
= _text_openflags
451 # Setting O_TEMPORARY in the flags causes the OS to delete
452 # the file when it is closed. This is only supported by Windows.
453 if _os
.name
== 'nt' and delete
:
454 flags |
= _os
.O_TEMPORARY
456 (fd
, name
) = _mkstemp_inner(dir, prefix
, suffix
, flags
)
457 file = _os
.fdopen(fd
, mode
, bufsize
)
458 return _TemporaryFileWrapper(file, name
, delete
)
460 if _os
.name
!= 'posix' or _os
.sys
.platform
== 'cygwin':
461 # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
463 TemporaryFile
= NamedTemporaryFile
466 def TemporaryFile(mode
='w+b', bufsize
=-1, suffix
="",
467 prefix
=template
, dir=None):
468 """Create and return a temporary file.
470 'prefix', 'suffix', 'dir' -- as for mkstemp.
471 'mode' -- the mode argument to os.fdopen (default "w+b").
472 'bufsize' -- the buffer size argument to os.fdopen (default -1).
473 The file is created as mkstemp() would do it.
475 Returns an object with a file-like interface. The file has no
476 name, and will cease to exist when it is closed.
483 flags
= _bin_openflags
485 flags
= _text_openflags
487 (fd
, name
) = _mkstemp_inner(dir, prefix
, suffix
, flags
)
490 return _os
.fdopen(fd
, mode
, bufsize
)
495 class SpooledTemporaryFile
:
496 """Temporary file wrapper, specialized to switch from
497 StringIO to a real file when it exceeds a certain size or
498 when a fileno is needed.
502 def __init__(self
, max_size
=0, mode
='w+b', bufsize
=-1,
503 suffix
="", prefix
=template
, dir=None):
504 self
._file
= _StringIO()
505 self
._max
_size
= max_size
507 self
._TemporaryFileArgs
= (mode
, bufsize
, suffix
, prefix
, dir)
509 def _check(self
, file):
510 if self
._rolled
: return
511 max_size
= self
._max
_size
512 if max_size
and file.tell() > max_size
:
516 if self
._rolled
: return
518 newfile
= self
._file
= TemporaryFile(*self
._TemporaryFileArgs
)
519 del self
._TemporaryFileArgs
521 newfile
.write(file.getvalue())
522 newfile
.seek(file.tell(), 0)
526 # The method caching trick from NamedTemporaryFile
527 # won't work here, because _file may change from a
528 # _StringIO instance to a real file. So we list
529 # all the methods directly.
531 # Context management protocol
533 if self
._file
.closed
:
534 raise ValueError("Cannot enter context with closed file")
537 def __exit__(self
, exc
, value
, tb
):
542 return self
._file
.__iter
__()
549 return self
._file
.closed
553 return self
._file
.encoding
557 return self
._file
.fileno()
563 return self
._file
.isatty()
567 return self
._file
.mode
571 return self
._file
.name
575 return self
._file
.newlines
578 return self
._file
.next
580 def read(self
, *args
):
581 return self
._file
.read(*args
)
583 def readline(self
, *args
):
584 return self
._file
.readline(*args
)
586 def readlines(self
, *args
):
587 return self
._file
.readlines(*args
)
589 def seek(self
, *args
):
590 self
._file
.seek(*args
)
594 return self
._file
.softspace
597 return self
._file
.tell()
600 self
._file
.truncate()
608 def writelines(self
, iterable
):
610 rv
= file.writelines(iterable
)
614 def xreadlines(self
, *args
):
615 return self
._file
.xreadlines(*args
)