home *** CD-ROM | disk | FTP | other *** search
/ linuxmafia.com 2016 / linuxmafia.com.tar / linuxmafia.com / pub / palmos / pippy-0.6beta-src.tar.gz / pippy-0.6beta-src.tar / pippy-0.6beta-src / src / Lib / tempfile.py < prev    next >
Text File  |  2000-12-21  |  4KB  |  141 lines

  1. """Temporary files and filenames."""
  2.  
  3. # XXX This tries to be not UNIX specific, but I don't know beans about
  4. # how to choose a temp directory or filename on MS-DOS or other
  5. # systems so it may have to be changed...
  6.  
  7.  
  8. import os
  9.  
  10.  
  11. # Parameters that the caller may set to override the defaults
  12.  
  13. tempdir = None
  14. template = None
  15.  
  16.  
  17. def gettempdir():
  18.     """Function to calculate the directory to use."""
  19.     global tempdir
  20.     if tempdir is not None:
  21.         return tempdir
  22.     try:
  23.         pwd = os.getcwd()
  24.     except (AttributeError, os.error):
  25.         pwd = os.curdir
  26.     attempdirs = ['/usr/tmp', '/tmp', pwd]
  27.     if os.name == 'nt':
  28.         attempdirs.insert(0, 'C:\\TEMP')
  29.         attempdirs.insert(0, '\\TEMP')
  30.     elif os.name == 'mac':
  31.         import macfs, MACFS
  32.         try:
  33.              refnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk,
  34.                                               MACFS.kTemporaryFolderType, 1)
  35.              dirname = macfs.FSSpec((refnum, dirid, '')).as_pathname()
  36.              attempdirs.insert(0, dirname)
  37.         except macfs.error:
  38.             pass
  39.     for envname in 'TMPDIR', 'TEMP', 'TMP':
  40.         if os.environ.has_key(envname):
  41.             attempdirs.insert(0, os.environ[envname])
  42.     testfile = gettempprefix() + 'test'
  43.     for dir in attempdirs:
  44.         try:
  45.             filename = os.path.join(dir, testfile)
  46.             fp = open(filename, 'w')
  47.             fp.write('blat')
  48.             fp.close()
  49.             os.unlink(filename)
  50.             tempdir = dir
  51.             break
  52.         except IOError:
  53.             pass
  54.     if tempdir is None:
  55.         msg = "Can't find a usable temporary directory amongst " + `attempdirs`
  56.         raise IOError, msg
  57.     return tempdir
  58.  
  59.  
  60. _pid = None
  61.  
  62. def gettempprefix():
  63.     """Function to calculate a prefix of the filename to use."""
  64.     global template, _pid
  65.     if os.name == 'posix' and _pid and _pid != os.getpid():
  66.         # Our pid changed; we must have forked -- zap the template
  67.         template = None
  68.     if template is None:
  69.         if os.name == 'posix':
  70.             _pid = os.getpid()
  71.             template = '@' + `_pid` + '.'
  72.         elif os.name == 'nt':
  73.             template = '~' + `os.getpid()` + '-'
  74.         elif os.name == 'mac':
  75.             template = 'Python-Tmp-'
  76.         else:
  77.             template = 'tmp' # XXX might choose a better one
  78.     return template
  79.  
  80.  
  81. # Counter for generating unique names
  82.  
  83. counter = 0
  84.  
  85.  
  86. def mktemp(suffix=""):
  87.     """User-callable function to return a unique temporary file name."""
  88.     global counter
  89.     dir = gettempdir()
  90.     pre = gettempprefix()
  91.     while 1:
  92.         counter = counter + 1
  93.         file = os.path.join(dir, pre + `counter` + suffix)
  94.         if not os.path.exists(file):
  95.             return file
  96.  
  97.  
  98. class TemporaryFileWrapper:
  99.     """Temporary file wrapper
  100.  
  101.     This class provides a wrapper around files opened for temporary use.
  102.     In particular, it seeks to automatically remove the file when it is
  103.     no longer needed.
  104.     """
  105.     def __init__(self, file, path):
  106.         self.file = file
  107.         self.path = path
  108.  
  109.     def close(self):
  110.         self.file.close()
  111.         os.unlink(self.path)
  112.  
  113.     def __del__(self):
  114.         try: self.close()
  115.         except: pass
  116.  
  117.     def __getattr__(self, name):
  118.         file = self.__dict__['file']
  119.         a = getattr(file, name)
  120.         if type(a) != type(0):
  121.             setattr(self, name, a)
  122.         return a
  123.  
  124.  
  125. def TemporaryFile(mode='w+b', bufsize=-1, suffix=""):
  126.     """Create and return a temporary file (opened read-write by default)."""
  127.     name = mktemp(suffix)
  128.     if os.name == 'posix':
  129.         # Unix -- be very careful
  130.         fd = os.open(name, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700)
  131.         try:
  132.             os.unlink(name)
  133.             return os.fdopen(fd, mode, bufsize)
  134.         except:
  135.             os.close(fd)
  136.             raise
  137.     else:
  138.         # Non-unix -- can't unlink file that's still open, use wrapper
  139.         file = open(name, mode, bufsize)
  140.         return TemporaryFileWrapper(file, name)
  141.