blob: 7d7f92415d5fca35949f84646f954720f335449d [file] [log] [blame]
Guido van Rossume7b146f2000-02-04 15:28:42 +00001"""Temporary files and filenames."""
2
Guido van Rossum41f95031992-03-31 19:02:01 +00003# 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...
Guido van Rossumeee94981991-11-12 15:38:08 +00006
Guido van Rossum41f95031992-03-31 19:02:01 +00007import os
Guido van Rossumeee94981991-11-12 15:38:08 +00008
Guido van Rossum41f95031992-03-31 19:02:01 +00009# Parameters that the caller may set to override the defaults
Guido van Rossum41f95031992-03-31 19:02:01 +000010tempdir = None
11template = None
12
Guido van Rossum41f95031992-03-31 19:02:01 +000013def gettempdir():
Guido van Rossume7b146f2000-02-04 15:28:42 +000014 """Function to calculate the directory to use."""
Guido van Rossumf4aaf861996-05-28 23:31:34 +000015 global tempdir
Guido van Rossum4033ad71996-08-08 18:33:56 +000016 if tempdir is not None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000017 return tempdir
Guido van Rossum29e5f5d1998-04-09 14:27:57 +000018 try:
19 pwd = os.getcwd()
20 except (AttributeError, os.error):
21 pwd = os.curdir
Guido van Rossume504c0c2000-08-29 14:55:03 +000022 attempdirs = ['/var/tmp', '/usr/tmp', '/tmp', pwd]
Guido van Rossum3e065ad1996-08-20 20:38:59 +000023 if os.name == 'nt':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000024 attempdirs.insert(0, 'C:\\TEMP')
25 attempdirs.insert(0, '\\TEMP')
Guido van Rossumf4f756c1997-04-11 19:00:53 +000026 elif os.name == 'mac':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000027 import macfs, MACFS
28 try:
Tim Petersb90f89a2001-01-15 03:26:36 +000029 refnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk,
30 MACFS.kTemporaryFolderType, 1)
31 dirname = macfs.FSSpec((refnum, dirid, '')).as_pathname()
32 attempdirs.insert(0, dirname)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000033 except macfs.error:
34 pass
Guido van Rossumca549821997-08-12 18:00:12 +000035 for envname in 'TMPDIR', 'TEMP', 'TMP':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000036 if os.environ.has_key(envname):
37 attempdirs.insert(0, os.environ[envname])
Guido van Rossum3e065ad1996-08-20 20:38:59 +000038 testfile = gettempprefix() + 'test'
Guido van Rossumf4aaf861996-05-28 23:31:34 +000039 for dir in attempdirs:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000040 try:
Tim Petersb90f89a2001-01-15 03:26:36 +000041 filename = os.path.join(dir, testfile)
42 if os.name == 'posix':
43 try:
Jeremy Hyltonc348cd72001-02-19 15:34:10 +000044 fd = os.open(filename,
45 os.O_RDWR | os.O_CREAT | os.O_EXCL, 0700)
Tim Petersb90f89a2001-01-15 03:26:36 +000046 except OSError:
47 pass
48 else:
49 fp = os.fdopen(fd, 'w')
50 fp.write('blat')
51 fp.close()
52 os.unlink(filename)
53 del fp, fd
54 tempdir = dir
55 break
56 else:
57 fp = open(filename, 'w')
58 fp.write('blat')
59 fp.close()
60 os.unlink(filename)
61 tempdir = dir
62 break
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000063 except IOError:
64 pass
Guido van Rossumf4aaf861996-05-28 23:31:34 +000065 if tempdir is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000066 msg = "Can't find a usable temporary directory amongst " + `attempdirs`
67 raise IOError, msg
Guido van Rossumf4aaf861996-05-28 23:31:34 +000068 return tempdir
Guido van Rossum41f95031992-03-31 19:02:01 +000069
70
Tim Peters9fadfb02001-01-13 03:04:02 +000071# template caches the result of gettempprefix, for speed, when possible.
72# XXX unclear why this isn't "_template"; left it "template" for backward
73# compatibility.
74if os.name == "posix":
75 # We don't try to cache the template on posix: the pid may change on us
76 # between calls due to a fork, and on Linux the pid changes even for
77 # another thread in the same process. Since any attempt to keep the
78 # cache in synch would have to call os.getpid() anyway in order to make
79 # sure the pid hasn't changed between calls, a cache wouldn't save any
80 # time. In addition, a cache is difficult to keep correct with the pid
81 # changing willy-nilly, and earlier attempts proved buggy (races).
82 template = None
83
84# Else the pid never changes, so gettempprefix always returns the same
85# string.
86elif os.name == "nt":
87 template = '~' + `os.getpid()` + '-'
88elif os.name == 'mac':
89 template = 'Python-Tmp-'
90else:
91 template = 'tmp' # XXX might choose a better one
Guido van Rossumb0e57181998-10-14 20:27:05 +000092
Guido van Rossum41f95031992-03-31 19:02:01 +000093def gettempprefix():
Tim Peters9fadfb02001-01-13 03:04:02 +000094 """Function to calculate a prefix of the filename to use.
95
96 This incorporates the current process id on systems that support such a
97 notion, so that concurrent processes don't generate the same prefix.
98 """
99
Tim Peters83732182001-01-14 05:12:40 +0000100 global template
Guido van Rossumb0e57181998-10-14 20:27:05 +0000101 if template is None:
Tim Peters83732182001-01-14 05:12:40 +0000102 return '@' + `os.getpid()` + '.'
Tim Peters9fadfb02001-01-13 03:04:02 +0000103 else:
104 return template
Guido van Rossumcff34541992-01-14 18:31:56 +0000105
Guido van Rossumeee94981991-11-12 15:38:08 +0000106
Guido van Rossumb8c42c91997-12-19 04:29:50 +0000107def mktemp(suffix=""):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000108 """User-callable function to return a unique temporary file name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000109 dir = gettempdir()
110 pre = gettempprefix()
111 while 1:
Tim Peters1baa22a2001-01-12 10:02:46 +0000112 i = _counter.get_next()
113 file = os.path.join(dir, pre + str(i) + suffix)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000114 if not os.path.exists(file):
115 return file
Guido van Rossumca549821997-08-12 18:00:12 +0000116
117
118class TemporaryFileWrapper:
119 """Temporary file wrapper
120
121 This class provides a wrapper around files opened for temporary use.
122 In particular, it seeks to automatically remove the file when it is
123 no longer needed.
124 """
125 def __init__(self, file, path):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000126 self.file = file
127 self.path = path
Guido van Rossumca549821997-08-12 18:00:12 +0000128
129 def close(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000130 self.file.close()
131 os.unlink(self.path)
Guido van Rossumca549821997-08-12 18:00:12 +0000132
133 def __del__(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000134 try: self.close()
135 except: pass
Guido van Rossumca549821997-08-12 18:00:12 +0000136
137 def __getattr__(self, name):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000138 file = self.__dict__['file']
139 a = getattr(file, name)
Guido van Rossum6b708d51999-06-01 18:55:36 +0000140 if type(a) != type(0):
141 setattr(self, name, a)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000142 return a
Guido van Rossumca549821997-08-12 18:00:12 +0000143
144
Guido van Rossumb8c42c91997-12-19 04:29:50 +0000145def TemporaryFile(mode='w+b', bufsize=-1, suffix=""):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000146 """Create and return a temporary file (opened read-write by default)."""
Guido van Rossumb8c42c91997-12-19 04:29:50 +0000147 name = mktemp(suffix)
Guido van Rossumdce3d551998-10-24 01:34:45 +0000148 if os.name == 'posix':
149 # Unix -- be very careful
150 fd = os.open(name, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700)
Guido van Rossum2457fc21998-10-24 15:02:59 +0000151 try:
152 os.unlink(name)
153 return os.fdopen(fd, mode, bufsize)
154 except:
155 os.close(fd)
156 raise
Guido van Rossumca549821997-08-12 18:00:12 +0000157 else:
Guido van Rossumdce3d551998-10-24 01:34:45 +0000158 # Non-unix -- can't unlink file that's still open, use wrapper
159 file = open(name, mode, bufsize)
160 return TemporaryFileWrapper(file, name)
Tim Peters1baa22a2001-01-12 10:02:46 +0000161
162# In order to generate unique names, mktemp() uses _counter.get_next().
163# This returns a unique integer on each call, in a threadsafe way (i.e.,
164# multiple threads will never see the same integer). The integer will
165# usually be a Python int, but if _counter.get_next() is called often
166# enough, it will become a Python long.
167# Note that the only name that survives this next block of code
168# is "_counter".
169
170class _ThreadSafeCounter:
171 def __init__(self, mutex, initialvalue=0):
172 self.mutex = mutex
173 self.i = initialvalue
174
175 def get_next(self):
176 self.mutex.acquire()
177 result = self.i
178 try:
179 newi = result + 1
180 except OverflowError:
181 newi = long(result) + 1
182 self.i = newi
183 self.mutex.release()
184 return result
185
186try:
187 import thread
188
189except ImportError:
190 class _DummyMutex:
191 def acquire(self):
192 pass
193
194 release = acquire
195
196 _counter = _ThreadSafeCounter(_DummyMutex())
197 del _DummyMutex
198
199else:
200 _counter = _ThreadSafeCounter(thread.allocate_lock())
201 del thread
202
203del _ThreadSafeCounter