home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyos2bin.zip / Lib / tempfile.py < prev    next >
Text File  |  1997-12-18  |  3KB  |  127 lines

  1. # Temporary file name allocation
  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. # Function to calculate the directory to use
  18.  
  19. def gettempdir():
  20.     global tempdir
  21.     if tempdir is not None:
  22.     return tempdir
  23.     attempdirs = ['/usr/tmp', '/tmp', os.getcwd(), os.curdir]
  24.     if os.name == 'nt':
  25.     attempdirs.insert(0, 'C:\\TEMP')
  26.     attempdirs.insert(0, '\\TEMP')
  27.     elif os.name == 'mac':
  28.         import macfs, MACFS
  29.         try:
  30.              refnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk,
  31.                           MACFS.kTemporaryFolderType, 0)
  32.              dirname = macfs.FSSpec((refnum, dirid, '')).as_pathname()
  33.              attempdirs.insert(0, dirname)
  34.     except macfs.error:
  35.         pass
  36.     for envname in 'TMPDIR', 'TEMP', 'TMP':
  37.     if os.environ.has_key(envname):
  38.         attempdirs.insert(0, os.environ[envname])
  39.     testfile = gettempprefix() + 'test'
  40.     for dir in attempdirs:
  41.     try:
  42.         filename = os.path.join(dir, testfile)
  43.         fp = open(filename, 'w')
  44.         fp.write('blat')
  45.         fp.close()
  46.         os.unlink(filename)
  47.         tempdir = dir
  48.         break
  49.     except IOError:
  50.         pass
  51.     if tempdir is None:
  52.     msg = "Can't find a usable temporary directory amongst " + `attempdirs`
  53.     raise IOError, msg
  54.     return tempdir
  55.  
  56.  
  57. # Function to calculate a prefix of the filename to use
  58.  
  59. def gettempprefix():
  60.     global template
  61.     if template == None:
  62.         if os.name == 'posix':
  63.             template = '@' + `os.getpid()` + '.'
  64.         elif os.name == 'nt':
  65.             template = '~' + `os.getpid()` + '-'
  66.         elif os.name == 'mac':
  67.             template = 'Python-Tmp-'
  68.         else:
  69.             template = 'tmp' # XXX might choose a better one
  70.     return template
  71.  
  72.  
  73. # Counter for generating unique names
  74.  
  75. counter = 0
  76.  
  77.  
  78. # User-callable function to return a unique temporary file name
  79.  
  80. def mktemp(suffix=""):
  81.     global counter
  82.     dir = gettempdir()
  83.     pre = gettempprefix()
  84.     while 1:
  85.         counter = counter + 1
  86.         file = os.path.join(dir, pre + `counter` + suffix)
  87.         if not os.path.exists(file):
  88.             return file
  89.  
  90.  
  91. class TemporaryFileWrapper:
  92.     """Temporary file wrapper
  93.  
  94.     This class provides a wrapper around files opened for temporary use.
  95.     In particular, it seeks to automatically remove the file when it is
  96.     no longer needed.
  97.     """
  98.     def __init__(self, file, path):
  99.     self.file = file
  100.     self.path = path
  101.  
  102.     def close(self):
  103.     self.file.close()
  104.     os.unlink(self.path)
  105.  
  106.     def __del__(self):
  107.     try: self.close()
  108.     except: pass
  109.  
  110.     def __getattr__(self, name):
  111.     file = self.__dict__['file']
  112.     a = getattr(file, name)
  113.     setattr(self, name, a)
  114.     return a
  115.  
  116.  
  117. def TemporaryFile(mode='w+b', bufsize=-1, suffix=""):
  118.     name = mktemp(suffix)
  119.     file = open(name, mode, bufsize)
  120.     try:
  121.     os.unlink(name)
  122.     except os.error:
  123.     # Non-unix -- can't unlink file that's still open, use wrapper
  124.     return TemporaryFileWrapper(file, name)
  125.     else:
  126.     return file
  127.