home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 7 / Apprentice-Release7.iso / Source Code / C / Applications / Python 1.4 / Python 1.4 source / Lib / tempfile.py < prev    next >
Encoding:
Text File  |  1996-08-26  |  1.6 KB  |  75 lines  |  [TEXT/Pyth]

  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.     if os.environ.has_key('TMPDIR'):
  28.     attempdirs.insert(0, os.environ['TMPDIR'])
  29.     testfile = gettempprefix() + 'test'
  30.     for dir in attempdirs:
  31.     try:
  32.         filename = os.path.join(dir, testfile)
  33.         fp = open(filename, 'w')
  34.         fp.write('blat')
  35.         fp.close()
  36.         os.unlink(filename)
  37.         tempdir = dir
  38.         break
  39.     except IOError:
  40.         pass
  41.     if tempdir is None:
  42.     msg = "Can't find a usable temporary directory amongst " + `attempdirs`
  43.     raise IOError, msg
  44.     return tempdir
  45.  
  46.  
  47. # Function to calculate a prefix of the filename to use
  48.  
  49. def gettempprefix():
  50.     global template
  51.     if template == None:
  52.         if os.name == 'posix':
  53.             template = '@' + `os.getpid()` + '.'
  54.         else:
  55.             template = 'tmp' # XXX might choose a better one
  56.     return template
  57.  
  58.  
  59. # Counter for generating unique names
  60.  
  61. counter = 0
  62.  
  63.  
  64. # User-callable function to return a unique temporary file name
  65.  
  66. def mktemp():
  67.     global counter
  68.     dir = gettempdir()
  69.     pre = gettempprefix()
  70.     while 1:
  71.         counter = counter + 1
  72.         file = os.path.join(dir, pre + `counter`)
  73.         if not os.path.exists(file):
  74.             return file
  75.