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"
34 import errno
as _errno
35 from random
import Random
as _Random
38 import fcntl
as _fcntl
45 flags
= _fcntl
.fcntl(fd
, _fcntl
.F_GETFD
, 0)
49 # flags read successfully, modify
50 flags |
= _fcntl
.FD_CLOEXEC
51 _fcntl
.fcntl(fd
, _fcntl
.F_SETFD
, flags
)
57 import _dummy_thread
as _thread
58 _allocate_lock
= _thread
.allocate_lock
60 _text_openflags
= _os
.O_RDWR | _os
.O_CREAT | _os
.O_EXCL
61 if hasattr(_os
, 'O_NOINHERIT'):
62 _text_openflags |
= _os
.O_NOINHERIT
63 if hasattr(_os
, 'O_NOFOLLOW'):
64 _text_openflags |
= _os
.O_NOFOLLOW
66 _bin_openflags
= _text_openflags
67 if hasattr(_os
, 'O_BINARY'):
68 _bin_openflags |
= _os
.O_BINARY
70 if hasattr(_os
, 'TMP_MAX'):
79 _once_lock
= _allocate_lock()
81 if hasattr(_os
, "lstat"):
83 elif hasattr(_os
, "stat"):
86 # Fallback. All we need is something that raises os.error if the
103 class _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.
109 _RandomNameSequence is an iterator."""
111 characters
= ("abcdefghijklmnopqrstuvwxyz" +
112 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
116 self
.mutex
= _allocate_lock()
118 self
.normcase
= _os
.path
.normcase
126 choose
= self
.rng
.choice
130 letters
= [choose(c
) for dummy
in "123456"]
134 return self
.normcase(''.join(letters
))
136 def _candidate_tempdir_list():
137 """Generate a list of candidate temporary directories which
138 _get_default_tempdir will try."""
142 # First, try the environment.
143 for envname
in 'TMPDIR', 'TEMP', 'TMP':
144 dirname
= _os
.getenv(envname
)
145 if dirname
: dirlist
.append(dirname
)
147 # Failing that, try OS-specific locations.
149 dirlist
.extend([ r
'c:\temp', r
'c:\tmp', r
'\temp', r
'\tmp' ])
151 dirlist
.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
153 # As a last resort, the current directory.
155 dirlist
.append(_os
.getcwd())
156 except (AttributeError, _os
.error
):
157 dirlist
.append(_os
.curdir
)
161 def _get_default_tempdir():
162 """Calculate the default directory to use for temporary files.
163 This routine should be called exactly once.
165 We determine whether or not a candidate temp dir is usable by
166 trying to create and write to a file in that directory. If this
167 is successful, the test file is deleted. To prevent denial of
168 service, the name of the test file must be randomized."""
170 namer
= _RandomNameSequence()
171 dirlist
= _candidate_tempdir_list()
172 flags
= _text_openflags
175 if dir != _os
.curdir
:
176 dir = _os
.path
.normcase(_os
.path
.abspath(dir))
177 # Try only a few names per directory.
178 for seq
in range(100):
180 filename
= _os
.path
.join(dir, name
)
182 fd
= _os
.open(filename
, flags
, 0o600)
183 fp
= _io
.open(fd
, 'wb')
189 except (OSError, IOError) as e
:
190 if e
.args
[0] != _errno
.EEXIST
:
191 break # no point trying more names in this directory
193 raise IOError(_errno
.ENOENT
,
194 "No usable temporary directory found in %s" % dirlist
)
196 _name_sequence
= None
198 def _get_candidate_names():
199 """Common setup sequence for all user-callable interfaces."""
201 global _name_sequence
202 if _name_sequence
is None:
205 if _name_sequence
is None:
206 _name_sequence
= _RandomNameSequence()
209 return _name_sequence
212 def _mkstemp_inner(dir, pre
, suf
, flags
):
213 """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
215 names
= _get_candidate_names()
217 for seq
in range(TMP_MAX
):
219 file = _os
.path
.join(dir, pre
+ name
+ suf
)
221 fd
= _os
.open(file, flags
, 0o600)
223 return (fd
, _os
.path
.abspath(file))
225 if e
.errno
== _errno
.EEXIST
:
229 raise IOError(_errno
.EEXIST
, "No usable temporary file name found")
232 # User visible interfaces.
235 """Accessor for tempdir.template."""
241 """Accessor for tempfile.tempdir."""
247 tempdir
= _get_default_tempdir()
252 def mkstemp(suffix
="", prefix
=template
, dir=None, text
=False):
253 """User-callable function to create and return a unique temporary
254 file. The return value is a pair (fd, name) where fd is the
255 file descriptor returned by os.open, and name is the filename.
257 If 'suffix' is specified, the file name will end with that suffix,
258 otherwise there will be no suffix.
260 If 'prefix' is specified, the file name will begin with that prefix,
261 otherwise a default prefix is used.
263 If 'dir' is specified, the file will be created in that directory,
264 otherwise a default directory is used.
266 If 'text' is specified and true, the file is opened in text
267 mode. Else (the default) the file is opened in binary mode. On
268 some operating systems, this makes no difference.
270 The file is readable and writable only by the creating user ID.
271 If the operating system uses permission bits to indicate whether a
272 file is executable, the file is executable by no one. The file
273 descriptor is not inherited by children of this process.
275 Caller is responsible for deleting the file when done with it.
282 flags
= _text_openflags
284 flags
= _bin_openflags
286 return _mkstemp_inner(dir, prefix
, suffix
, flags
)
289 def mkdtemp(suffix
="", prefix
=template
, dir=None):
290 """User-callable function to create and return a unique temporary
291 directory. The return value is the pathname of the directory.
293 Arguments are as for mkstemp, except that the 'text' argument is
296 The directory is readable, writable, and searchable only by the
299 Caller is responsible for deleting the directory when done with it.
305 names
= _get_candidate_names()
307 for seq
in range(TMP_MAX
):
309 file = _os
.path
.join(dir, prefix
+ name
+ suffix
)
311 _os
.mkdir(file, 0o700)
314 if e
.errno
== _errno
.EEXIST
:
318 raise IOError(_errno
.EEXIST
, "No usable temporary directory name found")
320 def mktemp(suffix
="", prefix
=template
, dir=None):
321 """User-callable function to return a unique temporary file name. The
324 Arguments are as for mkstemp, except that the 'text' argument is
327 This function is unsafe and should not be used. The file name
328 refers to a file that did not exist at some point, but by the time
329 you get around to creating it, someone else may have beaten you to
333 ## from warnings import warn as _warn
334 ## _warn("mktemp is a potential security risk to your program",
335 ## RuntimeWarning, stacklevel=2)
340 names
= _get_candidate_names()
341 for seq
in range(TMP_MAX
):
343 file = _os
.path
.join(dir, prefix
+ name
+ suffix
)
344 if not _exists(file):
347 raise IOError(_errno
.EEXIST
, "No usable temporary filename found")
350 class _TemporaryFileWrapper
:
351 """Temporary file wrapper
353 This class provides a wrapper around files opened for
354 temporary use. In particular, it seeks to automatically
355 remove the file when it is no longer needed.
358 def __init__(self
, file, name
, delete
=True):
361 self
.close_called
= False
364 def __getattr__(self
, name
):
365 # Attribute lookups are delegated to the underlying file
366 # and cached for non-numeric results
367 # (i.e. methods are cached, closed and friends are not)
368 file = self
.__dict
__['file']
369 a
= getattr(file, name
)
370 if not isinstance(a
, int):
371 setattr(self
, name
, a
)
374 # The underlying __enter__ method returns the wrong object
375 # (self.file) so override it to return the wrapper
377 self
.file.__enter
__()
380 # iter() doesn't use __getattr__ to find the __iter__ method
382 return iter(self
.file)
384 # NT provides delete-on-close as a primitive, so we don't need
385 # the wrapper to do anything special. We still use it so that
386 # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
388 # Cache the unlinker so we don't get spurious errors at
389 # shutdown when the module-level "os" is None'd out. Note
390 # that this must be referenced as self.unlink, because the
391 # name TemporaryFileWrapper may also get None'd out before
396 if not self
.close_called
:
397 self
.close_called
= True
400 self
.unlink(self
.name
)
405 # Need to trap __exit__ as well to ensure the file gets
406 # deleted when used in a with statement
407 def __exit__(self
, exc
, value
, tb
):
408 result
= self
.file.__exit
__(exc
, value
, tb
)
413 def NamedTemporaryFile(mode
='w+b', buffering
=-1, encoding
=None,
414 newline
=None, suffix
="", prefix
=template
,
415 dir=None, delete
=True):
416 """Create and return a temporary file.
418 'prefix', 'suffix', 'dir' -- as for mkstemp.
419 'mode' -- the mode argument to io.open (default "w+b").
420 'buffering' -- the buffer size argument to io.open (default -1).
421 'encoding' -- the encoding argument to io.open (default None)
422 'newline' -- the newline argument to io.open (default None)
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 = _io
.open(fd
, mode
, buffering
=buffering
,
446 newline
=newline
, encoding
=encoding
)
448 return _TemporaryFileWrapper(file, name
, delete
)
450 if _os
.name
!= 'posix' or _os
.sys
.platform
== 'cygwin':
451 # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
453 TemporaryFile
= NamedTemporaryFile
456 def TemporaryFile(mode
='w+b', buffering
=-1, encoding
=None,
457 newline
=None, suffix
="", prefix
=template
,
459 """Create and return a temporary file.
461 'prefix', 'suffix', 'dir' -- as for mkstemp.
462 'mode' -- the mode argument to io.open (default "w+b").
463 'buffering' -- the buffer size argument to io.open (default -1).
464 'encoding' -- the encoding argument to io.open (default None)
465 'newline' -- the newline argument to io.open (default None)
466 The file is created as mkstemp() would do it.
468 Returns an object with a file-like interface. The file has no
469 name, and will cease to exist when it is closed.
476 flags
= _bin_openflags
478 flags
= _text_openflags
480 (fd
, name
) = _mkstemp_inner(dir, prefix
, suffix
, flags
)
483 return _io
.open(fd
, mode
, buffering
=buffering
,
484 newline
=newline
, encoding
=encoding
)
489 class SpooledTemporaryFile
:
490 """Temporary file wrapper, specialized to switch from
491 StringIO to a real file when it exceeds a certain size or
492 when a fileno is needed.
496 def __init__(self
, max_size
=0, mode
='w+b', buffering
=-1,
497 encoding
=None, newline
=None,
498 suffix
="", prefix
=template
, dir=None):
500 self
._file
= _io
.BytesIO()
502 # Setting newline="\n" avoids newline translation;
503 # this is important because otherwise on Windows we'd
504 # hget double newline translation upon rollover().
505 self
._file
= _io
.StringIO(newline
="\n")
506 self
._max
_size
= max_size
508 self
._TemporaryFileArgs
= {'mode': mode
, 'buffering': buffering
,
509 'suffix': suffix
, 'prefix': prefix
,
510 'encoding': encoding
, 'newline': newline
,
513 def _check(self
, file):
514 if self
._rolled
: return
515 max_size
= self
._max
_size
516 if max_size
and file.tell() > max_size
:
520 if self
._rolled
: return
522 newfile
= self
._file
= TemporaryFile(**self
._TemporaryFileArgs
)
523 del self
._TemporaryFileArgs
525 newfile
.write(file.getvalue())
526 newfile
.seek(file.tell(), 0)
530 # The method caching trick from NamedTemporaryFile
531 # won't work here, because _file may change from a
532 # _StringIO instance to a real file. So we list
533 # all the methods directly.
535 # Context management protocol
537 if self
._file
.closed
:
538 raise ValueError("Cannot enter context with closed file")
541 def __exit__(self
, exc
, value
, tb
):
546 return self
._file
.__iter
__()
553 return self
._file
.closed
557 return self
._file
.encoding
561 return self
._file
.fileno()
567 return self
._file
.isatty()
571 return self
._file
.mode
575 return self
._file
.name
579 return self
._file
.newlines
582 return self
._file
.next
584 def read(self
, *args
):
585 return self
._file
.read(*args
)
587 def readline(self
, *args
):
588 return self
._file
.readline(*args
)
590 def readlines(self
, *args
):
591 return self
._file
.readlines(*args
)
593 def seek(self
, *args
):
594 self
._file
.seek(*args
)
598 return self
._file
.softspace
601 return self
._file
.tell()
604 self
._file
.truncate()
612 def writelines(self
, iterable
):
614 rv
= file.writelines(iterable
)
618 def xreadlines(self
, *args
):
619 return self
._file
.xreadlines(*args
)