ia64/xen-unstable

changeset 7044:0e2fdfe6b2bc

Remove unused tempfile.py. Even if anyone were using it, they shouldn't be --
there's tempfile functionality in the Python standard library.

Signed-off-by: Ewan Mellor <ewan@xensource.com>
author emellor@ewan
date Fri Sep 23 16:04:43 2005 +0100 (2005-09-23)
parents 64e3cab7ab9e
children 5805b47583ba
files
line diff
     1.1 --- a/tools/python/xen/util/tempfile.py	Fri Sep 23 15:53:36 2005 +0100
     1.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.3 @@ -1,451 +0,0 @@
     1.4 -"""Temporary files.
     1.5 -
     1.6 -This module provides generic, low- and high-level interfaces for
     1.7 -creating temporary files and directories.  The interfaces listed
     1.8 -as "safe" just below can be used without fear of race conditions.
     1.9 -Those listed as "unsafe" cannot, and are provided for backward
    1.10 -compatibility only.
    1.11 -
    1.12 -This module also provides some data items to the user:
    1.13 -
    1.14 -  TMP_MAX  - maximum number of names that will be tried before
    1.15 -             giving up.
    1.16 -  template - the default prefix for all temporary names.
    1.17 -             You may change this to control the default prefix.
    1.18 -  tempdir  - If this is set to a string before the first use of
    1.19 -             any routine from this module, it will be considered as
    1.20 -             another candidate location to store temporary files.
    1.21 -"""
    1.22 -
    1.23 -__all__ = [
    1.24 -    "NamedTemporaryFile", "TemporaryFile", # high level safe interfaces
    1.25 -    "mkstemp", "mkdtemp",                  # low level safe interfaces
    1.26 -    "mktemp",                              # deprecated unsafe interface
    1.27 -    "TMP_MAX", "gettempprefix",            # constants
    1.28 -    "tempdir", "gettempdir"
    1.29 -   ]
    1.30 -
    1.31 -
    1.32 -# Imports.
    1.33 -
    1.34 -import os as _os
    1.35 -import errno as _errno
    1.36 -from random import Random as _Random
    1.37 -
    1.38 -if _os.name == 'mac':
    1.39 -    import Carbon.Folder as _Folder
    1.40 -    import Carbon.Folders as _Folders
    1.41 -
    1.42 -try:
    1.43 -    import fcntl as _fcntl
    1.44 -    # If PYTHONCASEOK is set on Windows, stinking FCNTL.py gets
    1.45 -    # imported, and we don't get an ImportError then.  Provoke
    1.46 -    # an AttributeError instead in that case.
    1.47 -    _fcntl.fcntl
    1.48 -except (ImportError, AttributeError):
    1.49 -    def _set_cloexec(fd):
    1.50 -        pass
    1.51 -else:
    1.52 -    def _set_cloexec(fd):
    1.53 -        flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0)
    1.54 -        if flags >= 0:
    1.55 -            # flags read successfully, modify
    1.56 -            flags |= _fcntl.FD_CLOEXEC
    1.57 -            _fcntl.fcntl(fd, _fcntl.F_SETFD, flags)
    1.58 -
    1.59 -
    1.60 -try:
    1.61 -    import thread as _thread
    1.62 -except ImportError:
    1.63 -    import dummy_thread as _thread
    1.64 -_allocate_lock = _thread.allocate_lock
    1.65 -
    1.66 -_text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL
    1.67 -if hasattr(_os, 'O_NOINHERIT'):
    1.68 -    _text_openflags |= _os.O_NOINHERIT
    1.69 -if hasattr(_os, 'O_NOFOLLOW'):
    1.70 -    _text_openflags |= _os.O_NOFOLLOW
    1.71 -
    1.72 -_bin_openflags = _text_openflags
    1.73 -if hasattr(_os, 'O_BINARY'):
    1.74 -    _bin_openflags |= _os.O_BINARY
    1.75 -
    1.76 -if hasattr(_os, 'TMP_MAX'):
    1.77 -    TMP_MAX = _os.TMP_MAX
    1.78 -else:
    1.79 -    TMP_MAX = 10000
    1.80 -
    1.81 -template = "tmp"
    1.82 -
    1.83 -tempdir = None
    1.84 -
    1.85 -# Internal routines.
    1.86 -
    1.87 -_once_lock = _allocate_lock()
    1.88 -
    1.89 -class _RandomNameSequence:
    1.90 -    """An instance of _RandomNameSequence generates an endless
    1.91 -    sequence of unpredictable strings which can safely be incorporated
    1.92 -    into file names.  Each string is six characters long.  Multiple
    1.93 -    threads can safely use the same instance at the same time.
    1.94 -
    1.95 -    _RandomNameSequence is an iterator."""
    1.96 -
    1.97 -    characters = ("abcdefghijklmnopqrstuvwxyz" +
    1.98 -                  "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
    1.99 -                  "0123456789-_")
   1.100 -
   1.101 -    def __init__(self):
   1.102 -        self.mutex = _allocate_lock()
   1.103 -        self.rng = _Random()
   1.104 -        self.normcase = _os.path.normcase
   1.105 -
   1.106 -    def __iter__(self):
   1.107 -        return self
   1.108 -
   1.109 -    def next(self):
   1.110 -        m = self.mutex
   1.111 -        c = self.characters
   1.112 -        choose = self.rng.choice
   1.113 -
   1.114 -        m.acquire()
   1.115 -        try:
   1.116 -            letters = [choose(c) for dummy in "123456"]
   1.117 -        finally:
   1.118 -            m.release()
   1.119 -
   1.120 -        return self.normcase(''.join(letters))
   1.121 -
   1.122 -def _candidate_tempdir_list():
   1.123 -    """Generate a list of candidate temporary directories which
   1.124 -    _get_default_tempdir will try."""
   1.125 -
   1.126 -    dirlist = []
   1.127 -
   1.128 -    # First, try the environment.
   1.129 -    for envname in 'TMPDIR', 'TEMP', 'TMP':
   1.130 -        dirname = _os.getenv(envname)
   1.131 -        if dirname: dirlist.append(dirname)
   1.132 -
   1.133 -    # Failing that, try OS-specific locations.
   1.134 -    if _os.name == 'mac':
   1.135 -        try:
   1.136 -            fsr = _Folder.FSFindFolder(_Folders.kOnSystemDisk,
   1.137 -                                              _Folders.kTemporaryFolderType, 1)
   1.138 -            dirname = fsr.as_pathname()
   1.139 -            dirlist.append(dirname)
   1.140 -        except _Folder.error:
   1.141 -            pass
   1.142 -    elif _os.name == 'riscos':
   1.143 -        dirname = _os.getenv('Wimp$ScrapDir')
   1.144 -        if dirname: dirlist.append(dirname)
   1.145 -    elif _os.name == 'nt':
   1.146 -        dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
   1.147 -    else:
   1.148 -        dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
   1.149 -
   1.150 -    # As a last resort, the current directory.
   1.151 -    try:
   1.152 -        dirlist.append(_os.getcwd())
   1.153 -    except (AttributeError, _os.error):
   1.154 -        dirlist.append(_os.curdir)
   1.155 -
   1.156 -    return dirlist
   1.157 -
   1.158 -def _get_default_tempdir():
   1.159 -    """Calculate the default directory to use for temporary files.
   1.160 -    This routine should be called exactly once.
   1.161 -
   1.162 -    We determine whether or not a candidate temp dir is usable by
   1.163 -    trying to create and write to a file in that directory.  If this
   1.164 -    is successful, the test file is deleted.  To prevent denial of
   1.165 -    service, the name of the test file must be randomized."""
   1.166 -
   1.167 -    namer = _RandomNameSequence()
   1.168 -    dirlist = _candidate_tempdir_list()
   1.169 -    flags = _text_openflags
   1.170 -
   1.171 -    for dir in dirlist:
   1.172 -        if dir != _os.curdir:
   1.173 -            dir = _os.path.normcase(_os.path.abspath(dir))
   1.174 -        # Try only a few names per directory.
   1.175 -        for seq in xrange(100):
   1.176 -            name = namer.next()
   1.177 -            filename = _os.path.join(dir, name)
   1.178 -            try:
   1.179 -                fd = _os.open(filename, flags, 0600)
   1.180 -                fp = _os.fdopen(fd, 'w')
   1.181 -                fp.write('blat')
   1.182 -                fp.close()
   1.183 -                _os.unlink(filename)
   1.184 -                del fp, fd
   1.185 -                return dir
   1.186 -            except (OSError, IOError), e:
   1.187 -                if e[0] != _errno.EEXIST:
   1.188 -                    break # no point trying more names in this directory
   1.189 -                pass
   1.190 -    raise IOError, (_errno.ENOENT,
   1.191 -                    ("No usable temporary directory found in %s" % dirlist))
   1.192 -
   1.193 -_name_sequence = None
   1.194 -
   1.195 -def _get_candidate_names():
   1.196 -    """Common setup sequence for all user-callable interfaces."""
   1.197 -
   1.198 -    global _name_sequence
   1.199 -    if _name_sequence is None:
   1.200 -        _once_lock.acquire()
   1.201 -        try:
   1.202 -            if _name_sequence is None:
   1.203 -                _name_sequence = _RandomNameSequence()
   1.204 -        finally:
   1.205 -            _once_lock.release()
   1.206 -    return _name_sequence
   1.207 -
   1.208 -
   1.209 -def _mkstemp_inner(dir, pre, suf, flags):
   1.210 -    """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
   1.211 -
   1.212 -    names = _get_candidate_names()
   1.213 -
   1.214 -    for seq in xrange(TMP_MAX):
   1.215 -        name = names.next()
   1.216 -        file = _os.path.join(dir, pre + name + suf)
   1.217 -        try:
   1.218 -            fd = _os.open(file, flags, 0600)
   1.219 -            _set_cloexec(fd)
   1.220 -            return (fd, file)
   1.221 -        except OSError, e:
   1.222 -            if e.errno == _errno.EEXIST:
   1.223 -                continue # try again
   1.224 -            raise
   1.225 -
   1.226 -    raise IOError, (_errno.EEXIST, "No usable temporary file name found")
   1.227 -
   1.228 -
   1.229 -# User visible interfaces.
   1.230 -
   1.231 -def gettempprefix():
   1.232 -    """Accessor for tempdir.template."""
   1.233 -    return template
   1.234 -
   1.235 -tempdir = None
   1.236 -
   1.237 -def gettempdir():
   1.238 -    """Accessor for tempdir.tempdir."""
   1.239 -    global tempdir
   1.240 -    if tempdir is None:
   1.241 -        _once_lock.acquire()
   1.242 -        try:
   1.243 -            if tempdir is None:
   1.244 -                tempdir = _get_default_tempdir()
   1.245 -        finally:
   1.246 -            _once_lock.release()
   1.247 -    return tempdir
   1.248 -
   1.249 -def mkstemp(suffix="", prefix=template, dir=None, text=False):
   1.250 -    """mkstemp([suffix, [prefix, [dir, [text]]]])
   1.251 -    User-callable function to create and return a unique temporary
   1.252 -    file.  The return value is a pair (fd, name) where fd is the
   1.253 -    file descriptor returned by os.open, and name is the filename.
   1.254 -
   1.255 -    If 'suffix' is specified, the file name will end with that suffix,
   1.256 -    otherwise there will be no suffix.
   1.257 -
   1.258 -    If 'prefix' is specified, the file name will begin with that prefix,
   1.259 -    otherwise a default prefix is used.
   1.260 -
   1.261 -    If 'dir' is specified, the file will be created in that directory,
   1.262 -    otherwise a default directory is used.
   1.263 -
   1.264 -    If 'text' is specified and true, the file is opened in text
   1.265 -    mode.  Else (the default) the file is opened in binary mode.  On
   1.266 -    some operating systems, this makes no difference.
   1.267 -
   1.268 -    The file is readable and writable only by the creating user ID.
   1.269 -    If the operating system uses permission bits to indicate whether a
   1.270 -    file is executable, the file is executable by no one. The file
   1.271 -    descriptor is not inherited by children of this process.
   1.272 -
   1.273 -    Caller is responsible for deleting the file when done with it.
   1.274 -    """
   1.275 -
   1.276 -    if dir is None:
   1.277 -        dir = gettempdir()
   1.278 -
   1.279 -    if text:
   1.280 -        flags = _text_openflags
   1.281 -    else:
   1.282 -        flags = _bin_openflags
   1.283 -
   1.284 -    return _mkstemp_inner(dir, prefix, suffix, flags)
   1.285 -
   1.286 -
   1.287 -def mkdtemp(suffix="", prefix=template, dir=None):
   1.288 -    """mkdtemp([suffix, [prefix, [dir]]])
   1.289 -    User-callable function to create and return a unique temporary
   1.290 -    directory.  The return value is the pathname of the directory.
   1.291 -
   1.292 -    Arguments are as for mkstemp, except that the 'text' argument is
   1.293 -    not accepted.
   1.294 -
   1.295 -    The directory is readable, writable, and searchable only by the
   1.296 -    creating user.
   1.297 -
   1.298 -    Caller is responsible for deleting the directory when done with it.
   1.299 -    """
   1.300 -
   1.301 -    if dir is None:
   1.302 -        dir = gettempdir()
   1.303 -
   1.304 -    names = _get_candidate_names()
   1.305 -
   1.306 -    for seq in xrange(TMP_MAX):
   1.307 -        name = names.next()
   1.308 -        file = _os.path.join(dir, prefix + name + suffix)
   1.309 -        try:
   1.310 -            _os.mkdir(file, 0700)
   1.311 -            return file
   1.312 -        except OSError, e:
   1.313 -            if e.errno == _errno.EEXIST:
   1.314 -                continue # try again
   1.315 -            raise
   1.316 -
   1.317 -    raise IOError, (_errno.EEXIST, "No usable temporary directory name found")
   1.318 -
   1.319 -def mktemp(suffix="", prefix=template, dir=None):
   1.320 -    """mktemp([suffix, [prefix, [dir]]])
   1.321 -    User-callable function to return a unique temporary file name.  The
   1.322 -    file is not created.
   1.323 -
   1.324 -    Arguments are as for mkstemp, except that the 'text' argument is
   1.325 -    not accepted.
   1.326 -
   1.327 -    This function is unsafe and should not be used.  The file name
   1.328 -    refers to a file that did not exist at some point, but by the time
   1.329 -    you get around to creating it, someone else may have beaten you to
   1.330 -    the punch.
   1.331 -    """
   1.332 -
   1.333 -##    from warnings import warn as _warn
   1.334 -##    _warn("mktemp is a potential security risk to your program",
   1.335 -##          RuntimeWarning, stacklevel=2)
   1.336 -
   1.337 -    if dir is None:
   1.338 -        dir = gettempdir()
   1.339 -
   1.340 -    names = _get_candidate_names()
   1.341 -    for seq in xrange(TMP_MAX):
   1.342 -        name = names.next()
   1.343 -        file = _os.path.join(dir, prefix + name + suffix)
   1.344 -        if not _os.path.exists(file):
   1.345 -            return file
   1.346 -
   1.347 -    raise IOError, (_errno.EEXIST, "No usable temporary filename found")
   1.348 -
   1.349 -class _TemporaryFileWrapper:
   1.350 -    """Temporary file wrapper
   1.351 -
   1.352 -    This class provides a wrapper around files opened for
   1.353 -    temporary use.  In particular, it seeks to automatically
   1.354 -    remove the file when it is no longer needed.
   1.355 -    """
   1.356 -
   1.357 -    def __init__(self, file, name):
   1.358 -        self.file = file
   1.359 -        self.name = name
   1.360 -        self.close_called = False
   1.361 -
   1.362 -    def __getattr__(self, name):
   1.363 -        file = self.__dict__['file']
   1.364 -        a = getattr(file, name)
   1.365 -        if type(a) != type(0):
   1.366 -            setattr(self, name, a)
   1.367 -        return a
   1.368 -
   1.369 -    # NT provides delete-on-close as a primitive, so we don't need
   1.370 -    # the wrapper to do anything special.  We still use it so that
   1.371 -    # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
   1.372 -    if _os.name != 'nt':
   1.373 -
   1.374 -        # Cache the unlinker so we don't get spurious errors at
   1.375 -        # shutdown when the module-level "os" is None'd out.  Note
   1.376 -        # that this must be referenced as self.unlink, because the
   1.377 -        # name TemporaryFileWrapper may also get None'd out before
   1.378 -        # __del__ is called.
   1.379 -        unlink = _os.unlink
   1.380 -
   1.381 -        def close(self):
   1.382 -            if not self.close_called:
   1.383 -                self.close_called = True
   1.384 -                self.file.close()
   1.385 -                self.unlink(self.name)
   1.386 -
   1.387 -        def __del__(self):
   1.388 -            self.close()
   1.389 -
   1.390 -def NamedTemporaryFile(mode='w+b', bufsize=-1, suffix="",
   1.391 -                       prefix=template, dir=None):
   1.392 -    """Create and return a temporary file.
   1.393 -    Arguments:
   1.394 -    'prefix', 'suffix', 'dir' -- as for mkstemp.
   1.395 -    'mode' -- the mode argument to os.fdopen (default "w+b").
   1.396 -    'bufsize' -- the buffer size argument to os.fdopen (default -1).
   1.397 -    The file is created as mkstemp() would do it.
   1.398 -
   1.399 -    Returns a file object; the name of the file is accessible as
   1.400 -    file.name.  The file will be automatically deleted when it is
   1.401 -    closed.
   1.402 -    """
   1.403 -
   1.404 -    if dir is None:
   1.405 -        dir = gettempdir()
   1.406 -
   1.407 -    if 'b' in mode:
   1.408 -        flags = _bin_openflags
   1.409 -    else:
   1.410 -        flags = _text_openflags
   1.411 -
   1.412 -    # Setting O_TEMPORARY in the flags causes the OS to delete
   1.413 -    # the file when it is closed.  This is only supported by Windows.
   1.414 -    if _os.name == 'nt':
   1.415 -        flags |= _os.O_TEMPORARY
   1.416 -
   1.417 -    (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
   1.418 -    file = _os.fdopen(fd, mode, bufsize)
   1.419 -    return _TemporaryFileWrapper(file, name)
   1.420 -
   1.421 -if _os.name != 'posix' or _os.sys.platform == 'cygwin':
   1.422 -    # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
   1.423 -    # while it is open.
   1.424 -    TemporaryFile = NamedTemporaryFile
   1.425 -
   1.426 -else:
   1.427 -    def TemporaryFile(mode='w+b', bufsize=-1, suffix="",
   1.428 -                      prefix=template, dir=None):
   1.429 -        """Create and return a temporary file.
   1.430 -        Arguments:
   1.431 -        'prefix', 'suffix', 'directory' -- as for mkstemp.
   1.432 -        'mode' -- the mode argument to os.fdopen (default "w+b").
   1.433 -        'bufsize' -- the buffer size argument to os.fdopen (default -1).
   1.434 -        The file is created as mkstemp() would do it.
   1.435 -
   1.436 -        Returns a file object.  The file has no name, and will cease to
   1.437 -        exist when it is closed.
   1.438 -        """
   1.439 -
   1.440 -        if dir is None:
   1.441 -            dir = gettempdir()
   1.442 -
   1.443 -        if 'b' in mode:
   1.444 -            flags = _bin_openflags
   1.445 -        else:
   1.446 -            flags = _text_openflags
   1.447 -
   1.448 -        (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
   1.449 -        try:
   1.450 -            _os.unlink(name)
   1.451 -            return _os.fdopen(fd, mode, bufsize)
   1.452 -        except:
   1.453 -            _os.close(fd)
   1.454 -            raise