features/cdecimal / Lib /

The branch 'legacy-trunk' does not exist.
# Temporary file name allocation
# XXX This tries to be not UNIX specific, but I don't know beans about
# how to choose a temp directory or filename on MS-DOS or other
# systems so it may have to be changed...

import os

# Parameters that the caller may set to override the defaults

tempdir = None
template = None

# Function to calculate the directory to use

def gettempdir():
    global tempdir
    if tempdir is not None:
        return tempdir
        pwd = os.getcwd()
    except (AttributeError, os.error):
        pwd = os.curdir
    attempdirs = ['/usr/tmp', '/tmp', pwd]
    if == 'nt':
        attempdirs.insert(0, 'C:\\TEMP')
        attempdirs.insert(0, '\\TEMP')
    elif == 'mac':
        import macfs, MACFS
             refnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk,
                                              MACFS.kTemporaryFolderType, 1)
             dirname = macfs.FSSpec((refnum, dirid, '')).as_pathname()
             attempdirs.insert(0, dirname)
        except macfs.error:
    for envname in 'TMPDIR', 'TEMP', 'TMP':
        if os.environ.has_key(envname):
            attempdirs.insert(0, os.environ[envname])
    testfile = gettempprefix() + 'test'
    for dir in attempdirs:
            filename = os.path.join(dir, testfile)
            fp = open(filename, 'w')
            tempdir = dir
        except IOError:
    if tempdir is None:
        msg = "Can't find a usable temporary directory amongst " + `attempdirs`
        raise IOError, msg
    return tempdir

# Function to calculate a prefix of the filename to use

_pid = None

def gettempprefix():
    global template, _pid
    if == 'posix' and _pid and _pid != os.getpid():
        # Our pid changed; we must have forked -- zap the template
        template = None
    if template is None:
        if == 'posix':
            _pid = os.getpid()
            template = '@' + `_pid` + '.'
        elif == 'nt':
            template = '~' + `os.getpid()` + '-'
        elif == 'mac':
            template = 'Python-Tmp-'
            template = 'tmp' # XXX might choose a better one
    return template

# Counter for generating unique names

counter = 0

# User-callable function to return a unique temporary file name

def mktemp(suffix=""):
    global counter
    dir = gettempdir()
    pre = gettempprefix()
    while 1:
        counter = counter + 1
        file = os.path.join(dir, pre + `counter` + suffix)
        if not os.path.exists(file):
            return file

class TemporaryFileWrapper:
    """Temporary file wrapper

    This class provides a wrapper around files opened for temporary use.
    In particular, it seeks to automatically remove the file when it is
    no longer needed.
    def __init__(self, file, path):
        self.file = file
        self.path = path

    def close(self):

    def __del__(self):
        try: self.close()
        except: pass

    def __getattr__(self, name):
        file = self.__dict__['file']
        a = getattr(file, name)
        setattr(self, name, a)
        return a

def TemporaryFile(mode='w+b', bufsize=-1, suffix=""):
    name = mktemp(suffix)
    file = open(name, mode, bufsize)
    except os.error:
        # Non-unix -- can't unlink file that's still open, use wrapper
        return TemporaryFileWrapper(file, name)
        return file