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 "mkstemp", "mkdtemp", # low level safe interfaces
23 "mktemp", # deprecated unsafe interface
24 "TMP_MAX", "gettempprefix", # constants
25 "tempdir", "gettempdir"
32 import errno
as _errno
33 from random
import Random
as _Random
36 import Carbon
.Folder
as _Folder
37 import Carbon
.Folders
as _Folders
40 import fcntl
as _fcntl
47 flags
= _fcntl
.fcntl(fd
, _fcntl
.F_GETFD
, 0)
51 # flags read successfully, modify
52 flags |
= _fcntl
.FD_CLOEXEC
53 _fcntl
.fcntl(fd
, _fcntl
.F_SETFD
, flags
)
57 import thread
as _thread
59 import dummy_thread
as _thread
60 _allocate_lock
= _thread
.allocate_lock
62 _text_openflags
= _os
.O_RDWR | _os
.O_CREAT | _os
.O_EXCL
63 if hasattr(_os
, 'O_NOINHERIT'):
64 _text_openflags |
= _os
.O_NOINHERIT
65 if hasattr(_os
, 'O_NOFOLLOW'):
66 _text_openflags |
= _os
.O_NOFOLLOW
68 _bin_openflags
= _text_openflags
69 if hasattr(_os
, 'O_BINARY'):
70 _bin_openflags |
= _os
.O_BINARY
72 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
== 'mac':
154 fsr
= _Folder
.FSFindFolder(_Folders
.kOnSystemDisk
,
155 _Folders
.kTemporaryFolderType
, 1)
156 dirname
= fsr
.as_pathname()
157 dirlist
.append(dirname
)
158 except _Folder
.error
:
160 elif _os
.name
== 'riscos':
161 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' ])
166 dirlist
.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
168 # As a last resort, the current directory.
170 dirlist
.append(_os
.getcwd())
171 except (AttributeError, _os
.error
):
172 dirlist
.append(_os
.curdir
)
176 def _get_default_tempdir():
177 """Calculate the default directory to use for temporary files.
178 This routine should be called exactly once.
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."""
185 namer
= _RandomNameSequence()
186 dirlist
= _candidate_tempdir_list()
187 flags
= _text_openflags
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):
195 filename
= _os
.path
.join(dir, name
)
197 fd
= _os
.open(filename
, flags
, 0600)
198 fp
= _os
.fdopen(fd
, 'w')
204 except (OSError, IOError), e
:
205 if e
[0] != _errno
.EEXIST
:
206 break # no point trying more names in this directory
208 raise IOError, (_errno
.ENOENT
,
209 ("No usable temporary directory found in %s" % dirlist
))
211 _name_sequence
= None
213 def _get_candidate_names():
214 """Common setup sequence for all user-callable interfaces."""
216 global _name_sequence
217 if _name_sequence
is None:
220 if _name_sequence
is None:
221 _name_sequence
= _RandomNameSequence()
224 return _name_sequence
227 def _mkstemp_inner(dir, pre
, suf
, flags
):
228 """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
230 names
= _get_candidate_names()
232 for seq
in xrange(TMP_MAX
):
234 file = _os
.path
.join(dir, pre
+ name
+ suf
)
236 fd
= _os
.open(file, flags
, 0600)
238 return (fd
, _os
.path
.abspath(file))
240 if e
.errno
== _errno
.EEXIST
:
244 raise IOError, (_errno
.EEXIST
, "No usable temporary file name found")
247 # User visible interfaces.
250 """Accessor for tempdir.template."""
256 """Accessor for tempdir.tempdir."""
262 tempdir
= _get_default_tempdir()
267 def mkstemp(suffix
="", prefix
=template
, dir=None, text
=False):
268 """mkstemp([suffix, [prefix, [dir, [text]]]])
269 User-callable function to create and return a unique temporary
270 file. The return value is a pair (fd, name) where fd is the
271 file descriptor returned by os.open, and name is the filename.
273 If 'suffix' is specified, the file name will end with that suffix,
274 otherwise there will be no suffix.
276 If 'prefix' is specified, the file name will begin with that prefix,
277 otherwise a default prefix is used.
279 If 'dir' is specified, the file will be created in that directory,
280 otherwise a default directory is used.
282 If 'text' is specified and true, the file is opened in text
283 mode. Else (the default) the file is opened in binary mode. On
284 some operating systems, this makes no difference.
286 The file is readable and writable only by the creating user ID.
287 If the operating system uses permission bits to indicate whether a
288 file is executable, the file is executable by no one. The file
289 descriptor is not inherited by children of this process.
291 Caller is responsible for deleting the file when done with it.
298 flags
= _text_openflags
300 flags
= _bin_openflags
302 return _mkstemp_inner(dir, prefix
, suffix
, flags
)
305 def mkdtemp(suffix
="", prefix
=template
, dir=None):
306 """mkdtemp([suffix, [prefix, [dir]]])
307 User-callable function to create and return a unique temporary
308 directory. The return value is the pathname of the directory.
310 Arguments are as for mkstemp, except that the 'text' argument is
313 The directory is readable, writable, and searchable only by the
316 Caller is responsible for deleting the directory when done with it.
322 names
= _get_candidate_names()
324 for seq
in xrange(TMP_MAX
):
326 file = _os
.path
.join(dir, prefix
+ name
+ suffix
)
328 _os
.mkdir(file, 0700)
331 if e
.errno
== _errno
.EEXIST
:
335 raise IOError, (_errno
.EEXIST
, "No usable temporary directory name found")
337 def mktemp(suffix
="", prefix
=template
, dir=None):
338 """mktemp([suffix, [prefix, [dir]]])
339 User-callable function to return a unique temporary file name. The
342 Arguments are as for mkstemp, except that the 'text' argument is
345 This function is unsafe and should not be used. The file name
346 refers to a file that did not exist at some point, but by the time
347 you get around to creating it, someone else may have beaten you to
351 ## from warnings import warn as _warn
352 ## _warn("mktemp is a potential security risk to your program",
353 ## RuntimeWarning, stacklevel=2)
358 names
= _get_candidate_names()
359 for seq
in xrange(TMP_MAX
):
361 file = _os
.path
.join(dir, prefix
+ name
+ suffix
)
362 if not _exists(file):
365 raise IOError, (_errno
.EEXIST
, "No usable temporary filename found")
367 class _TemporaryFileWrapper
:
368 """Temporary file wrapper
370 This class provides a wrapper around files opened for
371 temporary use. In particular, it seeks to automatically
372 remove the file when it is no longer needed.
375 def __init__(self
, file, name
):
378 self
.close_called
= False
380 def __getattr__(self
, name
):
381 file = self
.__dict
__['file']
382 a
= getattr(file, name
)
383 if type(a
) != type(0):
384 setattr(self
, name
, a
)
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.
392 # Cache the unlinker so we don't get spurious errors at
393 # shutdown when the module-level "os" is None'd out. Note
394 # that this must be referenced as self.unlink, because the
395 # name TemporaryFileWrapper may also get None'd out before
400 if not self
.close_called
:
401 self
.close_called
= True
403 self
.unlink(self
.name
)
408 def NamedTemporaryFile(mode
='w+b', bufsize
=-1, suffix
="",
409 prefix
=template
, dir=None):
410 """Create and return a temporary file.
412 'prefix', 'suffix', 'dir' -- as for mkstemp.
413 'mode' -- the mode argument to os.fdopen (default "w+b").
414 'bufsize' -- the buffer size argument to os.fdopen (default -1).
415 The file is created as mkstemp() would do it.
417 Returns an object with a file-like interface; the name of the file
418 is accessible as file.name. The file will be automatically deleted
426 flags
= _bin_openflags
428 flags
= _text_openflags
430 # Setting O_TEMPORARY in the flags causes the OS to delete
431 # the file when it is closed. This is only supported by Windows.
433 flags |
= _os
.O_TEMPORARY
435 (fd
, name
) = _mkstemp_inner(dir, prefix
, suffix
, flags
)
436 file = _os
.fdopen(fd
, mode
, bufsize
)
437 return _TemporaryFileWrapper(file, name
)
439 if _os
.name
!= 'posix' or _os
.sys
.platform
== 'cygwin':
440 # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
442 TemporaryFile
= NamedTemporaryFile
445 def TemporaryFile(mode
='w+b', bufsize
=-1, suffix
="",
446 prefix
=template
, dir=None):
447 """Create and return a temporary file.
449 'prefix', 'suffix', 'directory' -- as for mkstemp.
450 'mode' -- the mode argument to os.fdopen (default "w+b").
451 'bufsize' -- the buffer size argument to os.fdopen (default -1).
452 The file is created as mkstemp() would do it.
454 Returns an object with a file-like interface. The file has no
455 name, and will cease to exist when it is closed.
462 flags
= _bin_openflags
464 flags
= _text_openflags
466 (fd
, name
) = _mkstemp_inner(dir, prefix
, suffix
, flags
)
469 return _os
.fdopen(fd
, mode
, bufsize
)