1 """Temporary files and filenames."""
9 __all__ = [
"mktemp",
"TemporaryFile",
"tempdir",
"gettempprefix"]
16 """Function to calculate the directory to use."""
18 if tempdir
is not None:
33 _tempdir_lock.acquire()
35 return _gettempdir_inner()
37 _tempdir_lock.release()
39 def _gettempdir_inner():
40 """Function to calculate the directory to use."""
42 if tempdir
is not None:
46 except (AttributeError, os.error):
48 attempdirs = [
'/tmp',
'/var/tmp',
'/usr/tmp', pwd]
50 attempdirs.insert(0,
'C:\\TEMP')
51 attempdirs.insert(0,
'\\TEMP')
52 elif os.name ==
'mac':
55 refnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk,
56 MACFS.kTemporaryFolderType, 1)
57 dirname = macfs.FSSpec((refnum, dirid,
'')).as_pathname()
58 attempdirs.insert(0, dirname)
61 elif os.name ==
'riscos':
64 attempdirs.insert(0, scrapdir)
65 for envname
in 'TMPDIR',
'TEMP',
'TMP':
66 if os.environ.has_key(envname):
67 attempdirs.insert(0, os.environ[envname])
69 for dir
in attempdirs:
71 filename = os.path.join(dir, testfile)
72 if os.name ==
'posix':
74 fd = os.open(filename,
75 os.O_RDWR | os.O_CREAT | os.O_EXCL, 0700)
79 fp = os.fdopen(fd,
'w')
87 fp =
open(filename,
'w')
96 msg =
"Can't find a usable temporary directory amongst " + `attempdirs`
104 if os.name ==
"posix":
116 elif os.name ==
"nt":
117 template =
'~' + `os.getpid()` +
'-'
118 elif os.name
in (
'mac',
'riscos'):
119 template =
'Python-Tmp-'
124 """Function to calculate a prefix of the filename to use.
126 This incorporates the current process id on systems that support such a
127 notion, so that concurrent processes don't generate the same prefix.
132 return '@' + `os.getpid()` +
'.'
138 """User-callable function to return a unique temporary file name."""
142 i = _counter.get_next()
143 file = os.path.join(dir, pre +
str(i) + suffix)
144 if not os.path.exists(file):
149 """Temporary file wrapper
151 This class provides a wrapper around files opened for temporary use.
152 In particular, it seeks to automatically remove the file when it is
177 file = self.__dict__[
'file']
178 a = getattr(file, name)
179 if type(a) != type(0):
180 setattr(self, name, a)
185 """Create and return a temporary file (opened read-write by default)."""
187 if os.name ==
'posix':
189 fd = os.open(name, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700)
192 return os.fdopen(fd, mode, bufsize)
198 file =
open(name, mode, bufsize)
212 self.
i = initialvalue
219 except OverflowError:
220 newi = long(result) + 1
241 _tempdir_lock = thread.allocate_lock()
244 del _ThreadSafeCounter