blob: f3cc4819ef5b6b4fce5e7baa49c7f35aa9edca03 [file] [log] [blame]
Guido van Rossum0e548712002-08-09 16:14:33 +00001"""Temporary files.
Guido van Rossume7b146f2000-02-04 15:28:42 +00002
Guido van Rossum0e548712002-08-09 16:14:33 +00003This module provides generic, low- and high-level interfaces for
4creating temporary files and directories. The interfaces listed
5as "safe" just below can be used without fear of race conditions.
6Those listed as "unsafe" cannot, and are provided for backward
7compatibility only.
Guido van Rossumeee94981991-11-12 15:38:08 +00008
Guido van Rossum0e548712002-08-09 16:14:33 +00009This module also provides some data items to the user:
Guido van Rossumeee94981991-11-12 15:38:08 +000010
Guido van Rossum0e548712002-08-09 16:14:33 +000011 TMP_MAX - maximum number of names that will be tried before
12 giving up.
13 template - the default prefix for all temporary names.
14 You may change this to control the default prefix.
15 tempdir - If this is set to a string before the first use of
16 any routine from this module, it will be considered as
17 another candidate location to store temporary files.
18"""
Skip Montanaro40fc1602001-03-01 04:27:19 +000019
Guido van Rossum0e548712002-08-09 16:14:33 +000020__all__ = [
21 "NamedTemporaryFile", "TemporaryFile", # high level safe interfaces
22 "mkstemp", "mkdtemp", # low level safe interfaces
23 "mktemp", # deprecated unsafe interface
24 "TMP_MAX", "gettempprefix", # constants
25 "tempdir", "gettempdir"
26 ]
Guido van Rossum41f95031992-03-31 19:02:01 +000027
Tim Peters4fd5a062002-01-28 23:11:23 +000028
Guido van Rossum0e548712002-08-09 16:14:33 +000029# Imports.
Tim Peters4fd5a062002-01-28 23:11:23 +000030
Guido van Rossum0e548712002-08-09 16:14:33 +000031import os as _os
32import errno as _errno
33from random import Random as _Random
34
35if _os.name == 'mac':
36 import macfs as _macfs
37 import MACFS as _MACFS
38
39try:
40 import fcntl as _fcntl
41 def _set_cloexec(fd):
42 flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0)
43 if flags >= 0:
44 # flags read successfully, modify
45 flags |= _fcntl.FD_CLOEXEC
46 _fcntl.fcntl(fd, _fcntl.F_SETFD, flags)
47except (ImportError, AttributeError):
48 def _set_cloexec(fd):
49 pass
50
51try:
52 import thread as _thread
53 _allocate_lock = _thread.allocate_lock
54except (ImportError, AttributeError):
55 class _allocate_lock:
56 def acquire(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000057 pass
Guido van Rossum0e548712002-08-09 16:14:33 +000058 release = acquire
59
60_text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL
61if hasattr(_os, 'O_NOINHERIT'): _text_openflags |= _os.O_NOINHERIT
62if hasattr(_os, 'O_NOFOLLOW'): _text_openflags |= _os.O_NOFOLLOW
63
64_bin_openflags = _text_openflags
65if hasattr(_os, 'O_BINARY'): _bin_openflags |= _os.O_BINARY
66
67if hasattr(_os, 'TMP_MAX'):
68 TMP_MAX = _os.TMP_MAX
69else:
70 TMP_MAX = 10000
71
72if _os.name == 'nt':
73 template = '~t' # cater to eight-letter limit
74else:
75 template = "tmp"
76
77tempdir = None
78
79# Internal routines.
80
81_once_lock = _allocate_lock()
82
83def _once(var, initializer):
84 """Wrapper to execute an initialization operation just once,
85 even if multiple threads reach the same point at the same time.
86
87 var is the name (as a string) of the variable to be entered into
88 the current global namespace.
89
90 initializer is a callable which will return the appropriate initial
91 value for variable. It will be called only if variable is not
92 present in the global namespace, or its current value is None.
93
94 Do not call _once from inside an initializer routine, it will deadlock.
95 """
96
97 vars = globals()
98 lock = _once_lock
99
100 # Check first outside the lock.
101 if var in vars and vars[var] is not None:
102 return
103 try:
104 lock.acquire()
105 # Check again inside the lock.
106 if var in vars and vars[var] is not None:
107 return
108 vars[var] = initializer()
109 finally:
110 lock.release()
111
112class _RandomNameSequence:
113 """An instance of _RandomNameSequence generates an endless
114 sequence of unpredictable strings which can safely be incorporated
115 into file names. Each string is six characters long. Multiple
116 threads can safely use the same instance at the same time.
117
118 _RandomNameSequence is an iterator."""
119
120 characters = ( "abcdefghijklmnopqrstuvwxyz"
121 + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
122 + "0123456789-_")
123
124 def __init__(self):
125 self.mutex = _allocate_lock()
126 self.rng = _Random()
127 self.normcase = _os.path.normcase
128 def __iter__(self):
129 return self
130
131 def next(self):
132 m = self.mutex
133 c = self.characters
134 r = self.rng
135
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000136 try:
Guido van Rossum0e548712002-08-09 16:14:33 +0000137 m.acquire()
138 letters = ''.join([r.choice(c), r.choice(c), r.choice(c),
139 r.choice(c), r.choice(c), r.choice(c)])
140 finally:
141 m.release()
142
143 return self.normcase(letters)
144
145def _candidate_tempdir_list():
146 """Generate a list of candidate temporary directories which
147 _get_default_tempdir will try."""
148
149 dirlist = []
150
151 # First, try the environment.
152 for envname in 'TMPDIR', 'TEMP', 'TMP':
153 dirname = _os.getenv(envname)
154 if dirname: dirlist.append(dirname)
155
156 # Failing that, try OS-specific locations.
157 if _os.name == 'mac':
158 try:
159 refnum, dirid = _macfs.FindFolder(_MACFS.kOnSystemDisk,
160 _MACFS.kTemporaryFolderType, 1)
161 dirname = _macfs.FSSpec((refnum, dirid, '')).as_pathname()
162 dirlist.append(dirname)
163 except _macfs.error:
164 pass
165 elif _os.name == 'riscos':
166 dirname = _os.getenv('Wimp$ScrapDir')
167 if dirname: dirlist.append(dirname)
168 elif _os.name == 'nt':
169 dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
170 else:
171 dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
172
173 # As a last resort, the current directory.
174 try:
175 dirlist.append(_os.getcwd())
176 except (AttributeError, _os.error):
177 dirlist.append(_os.curdir)
178
179 return dirlist
180
181def _get_default_tempdir():
182 """Calculate the default directory to use for temporary files.
183 This routine should be called through '_once' (see above) as we
184 do not want multiple threads attempting this calculation simultaneously.
185
186 We determine whether or not a candidate temp dir is usable by
187 trying to create and write to a file in that directory. If this
188 is successful, the test file is deleted. To prevent denial of
189 service, the name of the test file must be randomized."""
190
191 namer = _RandomNameSequence()
192 dirlist = _candidate_tempdir_list()
193 flags = _text_openflags
194
195 for dir in dirlist:
196 if dir != _os.curdir:
197 dir = _os.path.normcase(_os.path.abspath(dir))
198 # Try only a few names per directory.
199 for seq in xrange(100):
200 name = namer.next()
201 filename = _os.path.join(dir, name)
202 try:
203 fd = _os.open(filename, flags, 0600)
204 fp = _os.fdopen(fd, 'w')
Tim Petersb90f89a2001-01-15 03:26:36 +0000205 fp.write('blat')
206 fp.close()
Guido van Rossum0e548712002-08-09 16:14:33 +0000207 _os.unlink(filename)
208 del fp, fd
209 return dir
210 except (OSError, IOError), e:
211 if e[0] != _errno.EEXIST:
212 break # no point trying more names in this directory
213 pass
214 raise IOError, (_errno.ENOENT,
215 ("No usable temporary directory found in %s" % dirlist))
216
217def _get_candidate_names():
218 """Common setup sequence for all user-callable interfaces."""
219
220 _once('_name_sequence', _RandomNameSequence)
221 return _name_sequence
Guido van Rossum41f95031992-03-31 19:02:01 +0000222
223
Guido van Rossum0e548712002-08-09 16:14:33 +0000224def _mkstemp_inner(dir, pre, suf, flags):
225 """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
Tim Peters9fadfb02001-01-13 03:04:02 +0000226
Guido van Rossum0e548712002-08-09 16:14:33 +0000227 names = _get_candidate_names()
228
229 for seq in xrange(TMP_MAX):
230 name = names.next()
231 file = _os.path.join(dir, pre + name + suf)
232 try:
233 fd = _os.open(file, flags, 0600)
234 _set_cloexec(fd)
235 return (fd, file)
236 except OSError, e:
237 if e.errno == _errno.EEXIST:
238 continue # try again
239 raise
240
241 raise IOError, (_errno.EEXIST, "No usable temporary file name found")
242
243
244# User visible interfaces.
Guido van Rossumb0e57181998-10-14 20:27:05 +0000245
Guido van Rossum41f95031992-03-31 19:02:01 +0000246def gettempprefix():
Guido van Rossum0e548712002-08-09 16:14:33 +0000247 """Accessor for tempdir.template."""
248 return template
Tim Peters9fadfb02001-01-13 03:04:02 +0000249
Guido van Rossum0e548712002-08-09 16:14:33 +0000250def gettempdir():
251 """Accessor for tempdir.tempdir."""
252 _once('tempdir', _get_default_tempdir)
253 return tempdir
254
255def mkstemp(suffix="", prefix=template, dir=gettempdir(), binary=1):
256 """mkstemp([suffix, [prefix, [dir, [binary]]]])
257 User-callable function to create and return a unique temporary
258 file. The return value is a pair (fd, name) where fd is the
259 file descriptor returned by os.open, and name is the filename.
260
261 If 'suffix' is specified, the file name will end with that suffix,
262 otherwise there will be no suffix.
263
264 If 'prefix' is specified, the file name will begin with that prefix,
265 otherwise a default prefix is used.
266
267 If 'dir' is specified, the file will be created in that directory,
268 otherwise a default directory is used.
269
270 If 'binary' is specified and false, the file is opened in binary
271 mode. Otherwise, the file is opened in text mode. On some
272 operating systems, this makes no difference.
273
274 The file is readable and writable only by the creating user ID.
275 If the operating system uses permission bits to indicate whether a
276 file is executable, the file is executable by no one. The file
277 descriptor is not inherited by children of this process.
278
279 Caller is responsible for deleting the file when done with it.
Tim Peters9fadfb02001-01-13 03:04:02 +0000280 """
281
Guido van Rossum0e548712002-08-09 16:14:33 +0000282 if binary:
283 flags = _bin_openflags
Tim Peters9fadfb02001-01-13 03:04:02 +0000284 else:
Guido van Rossum0e548712002-08-09 16:14:33 +0000285 flags = _text_openflags
286
287 return _mkstemp_inner(dir, prefix, suffix, flags)
Guido van Rossumcff34541992-01-14 18:31:56 +0000288
Guido van Rossumeee94981991-11-12 15:38:08 +0000289
Guido van Rossum0e548712002-08-09 16:14:33 +0000290def mkdtemp(suffix="", prefix=template, dir=gettempdir()):
291 """mkdtemp([suffix, [prefix, [dir]]])
292 User-callable function to create and return a unique temporary
293 directory. The return value is the pathname of the directory.
294
295 Arguments are as for mkstemp, except that the 'binary' argument is
296 not accepted.
297
298 The directory is readable, writable, and searchable only by the
299 creating user.
300
301 Caller is responsible for deleting the directory when done with it.
302 """
303
304 names = _get_candidate_names()
305
306 for seq in xrange(TMP_MAX):
307 name = names.next()
308 file = _os.path.join(dir, prefix + name + suffix)
309 try:
310 _os.mkdir(file, 0700)
311 return file
312 except OSError, e:
313 if e.errno == _errno.EEXIST:
314 continue # try again
315 raise
316
317 raise IOError, (_errno.EEXIST, "No usable temporary directory name found")
318
319def mktemp(suffix="", prefix=template, dir=gettempdir()):
320 """mktemp([suffix, [prefix, [dir]]])
321 User-callable function to return a unique temporary file name. The
322 file is not created.
323
324 Arguments are as for mkstemp, except that the 'binary' argument is
325 not accepted.
326
327 This function is unsafe and should not be used. The file name
328 refers to a file that did not exist at some point, but by the time
329 you get around to creating it, someone else may have beaten you to
330 the punch.
331 """
332
333 from warnings import warn as _warn
334 _warn("mktemp is a potential security risk to your program",
335 RuntimeWarning, stacklevel=2)
336
337 names = _get_candidate_names()
338 for seq in xrange(TMP_MAX):
339 name = names.next()
340 file = _os.path.join(dir, prefix + name + suffix)
341 if not _os.path.exists(file):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000342 return file
Guido van Rossumca549821997-08-12 18:00:12 +0000343
Guido van Rossum0e548712002-08-09 16:14:33 +0000344 raise IOError, (_errno.EEXIST, "No usable temporary filename found")
Guido van Rossumca549821997-08-12 18:00:12 +0000345
Guido van Rossum0e548712002-08-09 16:14:33 +0000346class _TemporaryFileWrapper:
Guido van Rossumca549821997-08-12 18:00:12 +0000347 """Temporary file wrapper
348
Guido van Rossum0e548712002-08-09 16:14:33 +0000349 This class provides a wrapper around files opened for
350 temporary use. In particular, it seeks to automatically
351 remove the file when it is no longer needed.
Guido van Rossumca549821997-08-12 18:00:12 +0000352 """
Tim Petersa255a722001-12-18 22:32:40 +0000353
Guido van Rossum0e548712002-08-09 16:14:33 +0000354 def __init__(self, file, name):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000355 self.file = file
Guido van Rossum0e548712002-08-09 16:14:33 +0000356 self.name = name
Tim Petersc57a2852001-10-29 21:46:08 +0000357 self.close_called = 0
Guido van Rossumca549821997-08-12 18:00:12 +0000358
Guido van Rossumca549821997-08-12 18:00:12 +0000359 def __getattr__(self, name):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000360 file = self.__dict__['file']
361 a = getattr(file, name)
Guido van Rossum6b708d51999-06-01 18:55:36 +0000362 if type(a) != type(0):
363 setattr(self, name, a)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000364 return a
Guido van Rossumca549821997-08-12 18:00:12 +0000365
Guido van Rossum0e548712002-08-09 16:14:33 +0000366 # NT provides delete-on-close as a primitive, so we don't need
367 # the wrapper to do anything special. We still use it so that
368 # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
369 if _os.name != 'nt':
Guido van Rossumca549821997-08-12 18:00:12 +0000370
Guido van Rossum0e548712002-08-09 16:14:33 +0000371 # Cache the unlinker so we don't get spurious errors at
372 # shutdown when the module-level "os" is None'd out. Note
373 # that this must be referenced as self.unlink, because the
374 # name TemporaryFileWrapper may also get None'd out before
375 # __del__ is called.
376 unlink = _os.unlink
Tim Peters1baa22a2001-01-12 10:02:46 +0000377
Guido van Rossum0e548712002-08-09 16:14:33 +0000378 def close(self):
379 if not self.close_called:
380 self.close_called = 1
381 self.file.close()
382 self.unlink(self.name)
Tim Peters1baa22a2001-01-12 10:02:46 +0000383
Guido van Rossum0e548712002-08-09 16:14:33 +0000384 def __del__(self):
385 self.close()
Tim Peters1baa22a2001-01-12 10:02:46 +0000386
Guido van Rossum0e548712002-08-09 16:14:33 +0000387def NamedTemporaryFile(mode='w+b', bufsize=-1, suffix="",
388 prefix=template, dir=gettempdir()):
389 """Create and return a temporary file.
390 Arguments:
391 'prefix', 'suffix', 'dir' -- as for mkstemp.
392 'mode' -- the mode argument to os.fdopen (default "w+b").
393 'bufsize' -- the buffer size argument to os.fdopen (default -1).
394 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000395
Guido van Rossum0e548712002-08-09 16:14:33 +0000396 Returns a file object; the name of the file is accessible as
397 file.name. The file will be automatically deleted when it is
398 closed.
399 """
Tim Peters1baa22a2001-01-12 10:02:46 +0000400
Guido van Rossum0e548712002-08-09 16:14:33 +0000401 bin = 'b' in mode
402 if bin: flags = _bin_openflags
403 else: flags = _text_openflags
Tim Peters1baa22a2001-01-12 10:02:46 +0000404
Guido van Rossum0e548712002-08-09 16:14:33 +0000405 # Setting O_TEMPORARY in the flags causes the OS to delete
406 # the file when it is closed. This is only supported by Windows.
407 if _os.name == 'nt':
408 flags |= _os.O_TEMPORARY
Tim Peters1baa22a2001-01-12 10:02:46 +0000409
Guido van Rossum0e548712002-08-09 16:14:33 +0000410 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
411 file = _os.fdopen(fd, mode, bufsize)
412 return _TemporaryFileWrapper(file, name)
413
414if _os.name != 'posix':
415 # On non-POSIX systems, assume that we cannot unlink a file while
416 # it is open.
417 TemporaryFile = NamedTemporaryFile
Tim Peters1baa22a2001-01-12 10:02:46 +0000418
419else:
Guido van Rossum0e548712002-08-09 16:14:33 +0000420 def TemporaryFile(mode='w+b', bufsize=-1, suffix="",
421 prefix=template, dir=gettempdir()):
422 """Create and return a temporary file.
423 Arguments:
424 'prefix', 'suffix', 'directory' -- as for mkstemp.
425 'mode' -- the mode argument to os.fdopen (default "w+b").
426 'bufsize' -- the buffer size argument to os.fdopen (default -1).
427 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000428
Guido van Rossum0e548712002-08-09 16:14:33 +0000429 Returns a file object. The file has no name, and will cease to
430 exist when it is closed.
431 """
432
433 bin = 'b' in mode
434 if bin: flags = _bin_openflags
435 else: flags = _text_openflags
436
437 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
438 try:
439 _os.unlink(name)
440 return _os.fdopen(fd, mode, bufsize)
441 except:
442 _os.close(fd)
443 raise