Back to index

python3.2  3.2.2
Classes | Functions | Variables
tempfile Namespace Reference

Classes

class  _RandomNameSequence
class  _TemporaryFileWrapper
class  SpooledTemporaryFile
class  TemporaryDirectory

Functions

def _set_cloexec
def _stat
def _exists
def _candidate_tempdir_list
def _get_default_tempdir
def _get_candidate_names
def _mkstemp_inner
def gettempprefix
def gettempdir
def mkstemp
def mkdtemp
def mktemp
def NamedTemporaryFile
def TemporaryFile

Variables

list __all__
 _allocate_lock = _thread.allocate_lock
 _text_openflags = _os.O_RDWR|_os.O_CREAT|_os.O_EXCL
 _bin_openflags = _text_openflags
 TMP_MAX = _os.TMP_MAX
string template = "tmp"
tuple _once_lock = _allocate_lock()
 _stat = _os.lstat
 _name_sequence = None
 tempdir = None
tuple dir = gettempdir()
 from warnings import warn as _warn _warn("mktemp is a potential security risk to your program", RuntimeWarning, stacklevel=2)
tuple names = _get_candidate_names()
tuple name = next(names)
tuple file = _os.path.join(dir, prefix + name + suffix)
 TemporaryFile = NamedTemporaryFile

Detailed Description

Temporary files.

This module provides generic, low- and high-level interfaces for
creating temporary files and directories.  The interfaces listed
as "safe" just below can be used without fear of race conditions.
Those listed as "unsafe" cannot, and are provided for backward
compatibility only.

This module also provides some data items to the user:

  TMP_MAX  - maximum number of names that will be tried before
 giving up.
  template - the default prefix for all temporary names.
 You may change this to control the default prefix.
  tempdir  - If this is set to a string before the first use of
 any routine from this module, it will be considered as
 another candidate location to store temporary files.

Function Documentation

Generate a list of candidate temporary directories which
_get_default_tempdir will try.

Definition at line 127 of file tempfile.py.

00127 
00128 def _candidate_tempdir_list():
00129     """Generate a list of candidate temporary directories which
00130     _get_default_tempdir will try."""
00131 
00132     dirlist = []
00133 
00134     # First, try the environment.
00135     for envname in 'TMPDIR', 'TEMP', 'TMP':
00136         dirname = _os.getenv(envname)
00137         if dirname: dirlist.append(dirname)
00138 
00139     # Failing that, try OS-specific locations.
00140     if _os.name == 'nt':
00141         dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
00142     else:
00143         dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
00144 
00145     # As a last resort, the current directory.
00146     try:
00147         dirlist.append(_os.getcwd())
00148     except (AttributeError, _os.error):
00149         dirlist.append(_os.curdir)
00150 
00151     return dirlist

Here is the caller graph for this function:

def tempfile._exists (   fn) [private]

Definition at line 97 of file tempfile.py.

00097 
00098 def _exists(fn):
00099     try:
00100         _stat(fn)
00101     except _os.error:
00102         return False
00103     else:
00104         return True

def tempfile._get_candidate_names ( ) [private]
Common setup sequence for all user-callable interfaces.

Definition at line 188 of file tempfile.py.

00188 
00189 def _get_candidate_names():
00190     """Common setup sequence for all user-callable interfaces."""
00191 
00192     global _name_sequence
00193     if _name_sequence is None:
00194         _once_lock.acquire()
00195         try:
00196             if _name_sequence is None:
00197                 _name_sequence = _RandomNameSequence()
00198         finally:
00199             _once_lock.release()
00200     return _name_sequence
00201 

Here is the caller graph for this function:

def tempfile._get_default_tempdir ( ) [private]
Calculate the default directory to use for temporary files.
This routine should be called exactly once.

We determine whether or not a candidate temp dir is usable by
trying to create and write to a file in that directory.  If this
is successful, the test file is deleted.  To prevent denial of
service, the name of the test file must be randomized.

Definition at line 152 of file tempfile.py.

00152 
00153 def _get_default_tempdir():
00154     """Calculate the default directory to use for temporary files.
00155     This routine should be called exactly once.
00156 
00157     We determine whether or not a candidate temp dir is usable by
00158     trying to create and write to a file in that directory.  If this
00159     is successful, the test file is deleted.  To prevent denial of
00160     service, the name of the test file must be randomized."""
00161 
00162     namer = _RandomNameSequence()
00163     dirlist = _candidate_tempdir_list()
00164 
00165     for dir in dirlist:
00166         if dir != _os.curdir:
00167             dir = _os.path.normcase(_os.path.abspath(dir))
00168         # Try only a few names per directory.
00169         for seq in range(100):
00170             name = next(namer)
00171             filename = _os.path.join(dir, name)
00172             try:
00173                 fd = _os.open(filename, _bin_openflags, 0o600)
00174                 fp = _io.open(fd, 'wb')
00175                 fp.write(b'blat')
00176                 fp.close()
00177                 _os.unlink(filename)
00178                 del fp, fd
00179                 return dir
00180             except (OSError, IOError) as e:
00181                 if e.args[0] != _errno.EEXIST:
00182                     break # no point trying more names in this directory
00183                 pass
00184     raise IOError(_errno.ENOENT,
00185                   "No usable temporary directory found in %s" % dirlist)

Here is the call graph for this function:

Here is the caller graph for this function:

def tempfile._mkstemp_inner (   dir,
  pre,
  suf,
  flags 
) [private]
Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.

Definition at line 202 of file tempfile.py.

00202 
00203 def _mkstemp_inner(dir, pre, suf, flags):
00204     """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
00205 
00206     names = _get_candidate_names()
00207 
00208     for seq in range(TMP_MAX):
00209         name = next(names)
00210         file = _os.path.join(dir, pre + name + suf)
00211         try:
00212             fd = _os.open(file, flags, 0o600)
00213             _set_cloexec(fd)
00214             return (fd, _os.path.abspath(file))
00215         except OSError as e:
00216             if e.errno == _errno.EEXIST:
00217                 continue # try again
00218             raise
00219 
00220     raise IOError(_errno.EEXIST, "No usable temporary file name found")
00221 
00222 
00223 # User visible interfaces.

Here is the call graph for this function:

Here is the caller graph for this function:

def tempfile._set_cloexec (   fd) [private]

Definition at line 42 of file tempfile.py.

00042 
00043     def _set_cloexec(fd):
00044         pass
else:

Here is the caller graph for this function:

def tempfile._stat (   fn) [private]

Definition at line 90 of file tempfile.py.

00090 
00091     def _stat(fn):
00092         try:
00093             f = open(fn)
00094         except IOError:
00095             raise _os.error
00096         f.close()

Accessor for tempfile.tempdir.

Definition at line 230 of file tempfile.py.

00230 
00231 def gettempdir():
00232     """Accessor for tempfile.tempdir."""
00233     global tempdir
00234     if tempdir is None:
00235         _once_lock.acquire()
00236         try:
00237             if tempdir is None:
00238                 tempdir = _get_default_tempdir()
00239         finally:
00240             _once_lock.release()
00241     return tempdir

Here is the call graph for this function:

Here is the caller graph for this function:

Accessor for tempdir.template.

Definition at line 224 of file tempfile.py.

00224 
00225 def gettempprefix():
00226     """Accessor for tempdir.template."""
00227     return template

Here is the caller graph for this function:

def tempfile.mkdtemp (   suffix = "",
  prefix = template,
  dir = None 
)
User-callable function to create and return a unique temporary
directory.  The return value is the pathname of the directory.

Arguments are as for mkstemp, except that the 'text' argument is
not accepted.

The directory is readable, writable, and searchable only by the
creating user.

Caller is responsible for deleting the directory when done with it.

Definition at line 279 of file tempfile.py.

00279 
00280 def mkdtemp(suffix="", prefix=template, dir=None):
00281     """User-callable function to create and return a unique temporary
00282     directory.  The return value is the pathname of the directory.
00283 
00284     Arguments are as for mkstemp, except that the 'text' argument is
00285     not accepted.
00286 
00287     The directory is readable, writable, and searchable only by the
00288     creating user.
00289 
00290     Caller is responsible for deleting the directory when done with it.
00291     """
00292 
00293     if dir is None:
00294         dir = gettempdir()
00295 
00296     names = _get_candidate_names()
00297 
00298     for seq in range(TMP_MAX):
00299         name = next(names)
00300         file = _os.path.join(dir, prefix + name + suffix)
00301         try:
00302             _os.mkdir(file, 0o700)
00303             return file
00304         except OSError as e:
00305             if e.errno == _errno.EEXIST:
00306                 continue # try again
00307             raise
00308 
00309     raise IOError(_errno.EEXIST, "No usable temporary directory name found")

Here is the call graph for this function:

Here is the caller graph for this function:

def tempfile.mkstemp (   suffix = "",
  prefix = template,
  dir = None,
  text = False 
)
User-callable function to create and return a unique temporary
file.  The return value is a pair (fd, name) where fd is the
file descriptor returned by os.open, and name is the filename.

If 'suffix' is specified, the file name will end with that suffix,
otherwise there will be no suffix.

If 'prefix' is specified, the file name will begin with that prefix,
otherwise a default prefix is used.

If 'dir' is specified, the file will be created in that directory,
otherwise a default directory is used.

If 'text' is specified and true, the file is opened in text
mode.  Else (the default) the file is opened in binary mode.  On
some operating systems, this makes no difference.

The file is readable and writable only by the creating user ID.
If the operating system uses permission bits to indicate whether a
file is executable, the file is executable by no one. The file
descriptor is not inherited by children of this process.

Caller is responsible for deleting the file when done with it.

Definition at line 242 of file tempfile.py.

00242 
00243 def mkstemp(suffix="", prefix=template, dir=None, text=False):
00244     """User-callable function to create and return a unique temporary
00245     file.  The return value is a pair (fd, name) where fd is the
00246     file descriptor returned by os.open, and name is the filename.
00247 
00248     If 'suffix' is specified, the file name will end with that suffix,
00249     otherwise there will be no suffix.
00250 
00251     If 'prefix' is specified, the file name will begin with that prefix,
00252     otherwise a default prefix is used.
00253 
00254     If 'dir' is specified, the file will be created in that directory,
00255     otherwise a default directory is used.
00256 
00257     If 'text' is specified and true, the file is opened in text
00258     mode.  Else (the default) the file is opened in binary mode.  On
00259     some operating systems, this makes no difference.
00260 
00261     The file is readable and writable only by the creating user ID.
00262     If the operating system uses permission bits to indicate whether a
00263     file is executable, the file is executable by no one. The file
00264     descriptor is not inherited by children of this process.
00265 
00266     Caller is responsible for deleting the file when done with it.
00267     """
00268 
00269     if dir is None:
00270         dir = gettempdir()
00271 
00272     if text:
00273         flags = _text_openflags
00274     else:
00275         flags = _bin_openflags
00276 
00277     return _mkstemp_inner(dir, prefix, suffix, flags)
00278 

Here is the call graph for this function:

Here is the caller graph for this function:

def tempfile.mktemp (   suffix = "",
  prefix = template,
  dir = None 
)
User-callable function to return a unique temporary file name.  The
file is not created.

Arguments are as for mkstemp, except that the 'text' argument is
not accepted.

This function is unsafe and should not be used.  The file name
refers to a file that did not exist at some point, but by the time
you get around to creating it, someone else may have beaten you to
the punch.

Definition at line 310 of file tempfile.py.

00310 
00311 def mktemp(suffix="", prefix=template, dir=None):
00312     """User-callable function to return a unique temporary file name.  The
00313     file is not created.
00314 
00315     Arguments are as for mkstemp, except that the 'text' argument is
00316     not accepted.
00317 
00318     This function is unsafe and should not be used.  The file name
00319     refers to a file that did not exist at some point, but by the time
00320     you get around to creating it, someone else may have beaten you to
00321     the punch.
00322     """

Here is the caller graph for this function:

def tempfile.NamedTemporaryFile (   mode = 'w+b',
  buffering = -1,
  encoding = None,
  newline = None,
  suffix = "",
  prefix = template,
  dir = None,
  delete = True 
)
Create and return a temporary file.
Arguments:
'prefix', 'suffix', 'dir' -- as for mkstemp.
'mode' -- the mode argument to io.open (default "w+b").
'buffering' -- the buffer size argument to io.open (default -1).
'encoding' -- the encoding argument to io.open (default None)
'newline' -- the newline argument to io.open (default None)
'delete' -- whether the file is deleted on close (default True).
The file is created as mkstemp() would do it.

Returns an object with a file-like interface; the name of the file
is accessible as file.name.  The file will be automatically deleted
when it is closed unless the 'delete' argument is set to False.

Definition at line 408 of file tempfile.py.

00408 
00409                        dir=None, delete=True):
00410     """Create and return a temporary file.
00411     Arguments:
00412     'prefix', 'suffix', 'dir' -- as for mkstemp.
00413     'mode' -- the mode argument to io.open (default "w+b").
00414     'buffering' -- the buffer size argument to io.open (default -1).
00415     'encoding' -- the encoding argument to io.open (default None)
00416     'newline' -- the newline argument to io.open (default None)
00417     'delete' -- whether the file is deleted on close (default True).
00418     The file is created as mkstemp() would do it.
00419 
00420     Returns an object with a file-like interface; the name of the file
00421     is accessible as file.name.  The file will be automatically deleted
00422     when it is closed unless the 'delete' argument is set to False.
00423     """
00424 
00425     if dir is None:
00426         dir = gettempdir()
00427 
00428     flags = _bin_openflags
00429 
00430     # Setting O_TEMPORARY in the flags causes the OS to delete
00431     # the file when it is closed.  This is only supported by Windows.
00432     if _os.name == 'nt' and delete:
00433         flags |= _os.O_TEMPORARY
00434 
00435     (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
00436     file = _io.open(fd, mode, buffering=buffering,
00437                     newline=newline, encoding=encoding)
00438 
00439     return _TemporaryFileWrapper(file, name, delete)

Here is the call graph for this function:

Here is the caller graph for this function:

def tempfile.TemporaryFile (   mode = 'w+b',
  buffering = -1,
  encoding = None,
  newline = None,
  suffix = "",
  prefix = template,
  dir = None 
)
Create and return a temporary file.
Arguments:
'prefix', 'suffix', 'dir' -- as for mkstemp.
'mode' -- the mode argument to io.open (default "w+b").
'buffering' -- the buffer size argument to io.open (default -1).
'encoding' -- the encoding argument to io.open (default None)
'newline' -- the newline argument to io.open (default None)
The file is created as mkstemp() would do it.

Returns an object with a file-like interface.  The file has no
name, and will cease to exist when it is closed.

Definition at line 448 of file tempfile.py.

00448 
00449                       dir=None):
00450         """Create and return a temporary file.
00451         Arguments:
00452         'prefix', 'suffix', 'dir' -- as for mkstemp.
00453         'mode' -- the mode argument to io.open (default "w+b").
00454         'buffering' -- the buffer size argument to io.open (default -1).
00455         'encoding' -- the encoding argument to io.open (default None)
00456         'newline' -- the newline argument to io.open (default None)
00457         The file is created as mkstemp() would do it.
00458 
00459         Returns an object with a file-like interface.  The file has no
00460         name, and will cease to exist when it is closed.
00461         """
00462 
00463         if dir is None:
00464             dir = gettempdir()
00465 
00466         flags = _bin_openflags
00467 
00468         (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
00469         try:
00470             _os.unlink(name)
00471             return _io.open(fd, mode, buffering=buffering,
00472                             newline=newline, encoding=encoding)
00473         except:
00474             _os.close(fd)
00475             raise

Here is the call graph for this function:

Here is the caller graph for this function:


Variable Documentation

Initial value:
00001 [
00002     "NamedTemporaryFile", "TemporaryFile", # high level safe interfaces
00003     "SpooledTemporaryFile", "TemporaryDirectory",
00004     "mkstemp", "mkdtemp",                  # low level safe interfaces
00005     "mktemp",                              # deprecated unsafe interface
00006     "TMP_MAX", "gettempprefix",            # constants
00007     "tempdir", "gettempdir"
00008    ]

Definition at line 20 of file tempfile.py.

tempfile._allocate_lock = _thread.allocate_lock

Definition at line 60 of file tempfile.py.

Definition at line 68 of file tempfile.py.

Definition at line 186 of file tempfile.py.

Definition at line 81 of file tempfile.py.

tempfile._stat = _os.lstat

Definition at line 84 of file tempfile.py.

tempfile._text_openflags = _os.O_RDWR|_os.O_CREAT|_os.O_EXCL

Definition at line 62 of file tempfile.py.

from warnings import warn as _warn _warn("mktemp is a potential security risk to your program", RuntimeWarning, stacklevel=2)

Definition at line 328 of file tempfile.py.

tuple tempfile.file = _os.path.join(dir, prefix + name + suffix)

Definition at line 333 of file tempfile.py.

tuple tempfile.name = next(names)

Definition at line 332 of file tempfile.py.

Definition at line 330 of file tempfile.py.

Definition at line 228 of file tempfile.py.

Definition at line 77 of file tempfile.py.

Definition at line 443 of file tempfile.py.

int tempfile.TMP_MAX = _os.TMP_MAX

Definition at line 73 of file tempfile.py.