blob: 32b83a0801ce3fcc2248672cde5d7b8fc5dfe1ae [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
Tim Petersa0d55de2002-08-09 18:01:01 +000061if hasattr(_os, 'O_NOINHERIT'):
62 _text_openflags |= _os.O_NOINHERIT
63if hasattr(_os, 'O_NOFOLLOW'):
64 _text_openflags |= _os.O_NOFOLLOW
Guido van Rossum0e548712002-08-09 16:14:33 +000065
66_bin_openflags = _text_openflags
Tim Petersa0d55de2002-08-09 18:01:01 +000067if hasattr(_os, 'O_BINARY'):
68 _bin_openflags |= _os.O_BINARY
Guido van Rossum0e548712002-08-09 16:14:33 +000069
70if hasattr(_os, 'TMP_MAX'):
71 TMP_MAX = _os.TMP_MAX
72else:
73 TMP_MAX = 10000
74
75if _os.name == 'nt':
76 template = '~t' # cater to eight-letter limit
77else:
78 template = "tmp"
79
80tempdir = None
81
82# Internal routines.
83
84_once_lock = _allocate_lock()
85
86def _once(var, initializer):
87 """Wrapper to execute an initialization operation just once,
88 even if multiple threads reach the same point at the same time.
89
90 var is the name (as a string) of the variable to be entered into
91 the current global namespace.
92
93 initializer is a callable which will return the appropriate initial
94 value for variable. It will be called only if variable is not
95 present in the global namespace, or its current value is None.
96
97 Do not call _once from inside an initializer routine, it will deadlock.
98 """
99
100 vars = globals()
101 lock = _once_lock
102
103 # Check first outside the lock.
104 if var in vars and vars[var] is not None:
105 return
106 try:
107 lock.acquire()
108 # Check again inside the lock.
109 if var in vars and vars[var] is not None:
110 return
111 vars[var] = initializer()
112 finally:
113 lock.release()
114
115class _RandomNameSequence:
116 """An instance of _RandomNameSequence generates an endless
117 sequence of unpredictable strings which can safely be incorporated
118 into file names. Each string is six characters long. Multiple
119 threads can safely use the same instance at the same time.
120
121 _RandomNameSequence is an iterator."""
122
123 characters = ( "abcdefghijklmnopqrstuvwxyz"
124 + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
125 + "0123456789-_")
126
127 def __init__(self):
128 self.mutex = _allocate_lock()
129 self.rng = _Random()
130 self.normcase = _os.path.normcase
131 def __iter__(self):
132 return self
133
134 def next(self):
135 m = self.mutex
136 c = self.characters
137 r = self.rng
138
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000139 try:
Guido van Rossum0e548712002-08-09 16:14:33 +0000140 m.acquire()
141 letters = ''.join([r.choice(c), r.choice(c), r.choice(c),
142 r.choice(c), r.choice(c), r.choice(c)])
143 finally:
144 m.release()
145
146 return self.normcase(letters)
147
148def _candidate_tempdir_list():
149 """Generate a list of candidate temporary directories which
150 _get_default_tempdir will try."""
151
152 dirlist = []
153
154 # First, try the environment.
155 for envname in 'TMPDIR', 'TEMP', 'TMP':
156 dirname = _os.getenv(envname)
157 if dirname: dirlist.append(dirname)
158
159 # Failing that, try OS-specific locations.
160 if _os.name == 'mac':
161 try:
162 refnum, dirid = _macfs.FindFolder(_MACFS.kOnSystemDisk,
163 _MACFS.kTemporaryFolderType, 1)
164 dirname = _macfs.FSSpec((refnum, dirid, '')).as_pathname()
165 dirlist.append(dirname)
166 except _macfs.error:
167 pass
168 elif _os.name == 'riscos':
169 dirname = _os.getenv('Wimp$ScrapDir')
170 if dirname: dirlist.append(dirname)
171 elif _os.name == 'nt':
172 dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
173 else:
174 dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
175
176 # As a last resort, the current directory.
177 try:
178 dirlist.append(_os.getcwd())
179 except (AttributeError, _os.error):
180 dirlist.append(_os.curdir)
181
182 return dirlist
Tim Petersa0d55de2002-08-09 18:01:01 +0000183
Guido van Rossum0e548712002-08-09 16:14:33 +0000184def _get_default_tempdir():
185 """Calculate the default directory to use for temporary files.
186 This routine should be called through '_once' (see above) as we
187 do not want multiple threads attempting this calculation simultaneously.
188
189 We determine whether or not a candidate temp dir is usable by
190 trying to create and write to a file in that directory. If this
191 is successful, the test file is deleted. To prevent denial of
192 service, the name of the test file must be randomized."""
193
194 namer = _RandomNameSequence()
195 dirlist = _candidate_tempdir_list()
196 flags = _text_openflags
197
198 for dir in dirlist:
199 if dir != _os.curdir:
200 dir = _os.path.normcase(_os.path.abspath(dir))
201 # Try only a few names per directory.
202 for seq in xrange(100):
203 name = namer.next()
204 filename = _os.path.join(dir, name)
205 try:
206 fd = _os.open(filename, flags, 0600)
207 fp = _os.fdopen(fd, 'w')
Tim Petersb90f89a2001-01-15 03:26:36 +0000208 fp.write('blat')
209 fp.close()
Guido van Rossum0e548712002-08-09 16:14:33 +0000210 _os.unlink(filename)
211 del fp, fd
212 return dir
213 except (OSError, IOError), e:
214 if e[0] != _errno.EEXIST:
215 break # no point trying more names in this directory
216 pass
217 raise IOError, (_errno.ENOENT,
218 ("No usable temporary directory found in %s" % dirlist))
219
220def _get_candidate_names():
221 """Common setup sequence for all user-callable interfaces."""
222
223 _once('_name_sequence', _RandomNameSequence)
224 return _name_sequence
Guido van Rossum41f95031992-03-31 19:02:01 +0000225
226
Guido van Rossum0e548712002-08-09 16:14:33 +0000227def _mkstemp_inner(dir, pre, suf, flags):
228 """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
Tim Peters9fadfb02001-01-13 03:04:02 +0000229
Guido van Rossum0e548712002-08-09 16:14:33 +0000230 names = _get_candidate_names()
231
232 for seq in xrange(TMP_MAX):
233 name = names.next()
234 file = _os.path.join(dir, pre + name + suf)
235 try:
236 fd = _os.open(file, flags, 0600)
237 _set_cloexec(fd)
238 return (fd, file)
239 except OSError, e:
240 if e.errno == _errno.EEXIST:
241 continue # try again
242 raise
243
244 raise IOError, (_errno.EEXIST, "No usable temporary file name found")
Tim Petersa0d55de2002-08-09 18:01:01 +0000245
Guido van Rossum0e548712002-08-09 16:14:33 +0000246
247# User visible interfaces.
Guido van Rossumb0e57181998-10-14 20:27:05 +0000248
Guido van Rossum41f95031992-03-31 19:02:01 +0000249def gettempprefix():
Guido van Rossum0e548712002-08-09 16:14:33 +0000250 """Accessor for tempdir.template."""
251 return template
Tim Peters9fadfb02001-01-13 03:04:02 +0000252
Guido van Rossum0e548712002-08-09 16:14:33 +0000253def gettempdir():
254 """Accessor for tempdir.tempdir."""
255 _once('tempdir', _get_default_tempdir)
256 return tempdir
257
258def mkstemp(suffix="", prefix=template, dir=gettempdir(), binary=1):
259 """mkstemp([suffix, [prefix, [dir, [binary]]]])
260 User-callable function to create and return a unique temporary
261 file. The return value is a pair (fd, name) where fd is the
262 file descriptor returned by os.open, and name is the filename.
263
264 If 'suffix' is specified, the file name will end with that suffix,
265 otherwise there will be no suffix.
266
267 If 'prefix' is specified, the file name will begin with that prefix,
268 otherwise a default prefix is used.
269
270 If 'dir' is specified, the file will be created in that directory,
271 otherwise a default directory is used.
272
273 If 'binary' is specified and false, the file is opened in binary
274 mode. Otherwise, the file is opened in text mode. On some
275 operating systems, this makes no difference.
276
277 The file is readable and writable only by the creating user ID.
278 If the operating system uses permission bits to indicate whether a
279 file is executable, the file is executable by no one. The file
280 descriptor is not inherited by children of this process.
281
282 Caller is responsible for deleting the file when done with it.
Tim Peters9fadfb02001-01-13 03:04:02 +0000283 """
284
Guido van Rossum0e548712002-08-09 16:14:33 +0000285 if binary:
286 flags = _bin_openflags
Tim Peters9fadfb02001-01-13 03:04:02 +0000287 else:
Guido van Rossum0e548712002-08-09 16:14:33 +0000288 flags = _text_openflags
289
290 return _mkstemp_inner(dir, prefix, suffix, flags)
Guido van Rossumcff34541992-01-14 18:31:56 +0000291
Guido van Rossumeee94981991-11-12 15:38:08 +0000292
Guido van Rossum0e548712002-08-09 16:14:33 +0000293def mkdtemp(suffix="", prefix=template, dir=gettempdir()):
294 """mkdtemp([suffix, [prefix, [dir]]])
295 User-callable function to create and return a unique temporary
296 directory. The return value is the pathname of the directory.
297
298 Arguments are as for mkstemp, except that the 'binary' argument is
299 not accepted.
300
301 The directory is readable, writable, and searchable only by the
302 creating user.
303
304 Caller is responsible for deleting the directory when done with it.
305 """
306
307 names = _get_candidate_names()
Tim Petersa0d55de2002-08-09 18:01:01 +0000308
Guido van Rossum0e548712002-08-09 16:14:33 +0000309 for seq in xrange(TMP_MAX):
310 name = names.next()
311 file = _os.path.join(dir, prefix + name + suffix)
312 try:
313 _os.mkdir(file, 0700)
314 return file
315 except OSError, e:
316 if e.errno == _errno.EEXIST:
317 continue # try again
318 raise
319
320 raise IOError, (_errno.EEXIST, "No usable temporary directory name found")
321
322def mktemp(suffix="", prefix=template, dir=gettempdir()):
323 """mktemp([suffix, [prefix, [dir]]])
324 User-callable function to return a unique temporary file name. The
325 file is not created.
326
327 Arguments are as for mkstemp, except that the 'binary' argument is
328 not accepted.
329
330 This function is unsafe and should not be used. The file name
331 refers to a file that did not exist at some point, but by the time
332 you get around to creating it, someone else may have beaten you to
333 the punch.
334 """
335
336 from warnings import warn as _warn
337 _warn("mktemp is a potential security risk to your program",
338 RuntimeWarning, stacklevel=2)
339
340 names = _get_candidate_names()
341 for seq in xrange(TMP_MAX):
342 name = names.next()
343 file = _os.path.join(dir, prefix + name + suffix)
344 if not _os.path.exists(file):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000345 return file
Guido van Rossumca549821997-08-12 18:00:12 +0000346
Guido van Rossum0e548712002-08-09 16:14:33 +0000347 raise IOError, (_errno.EEXIST, "No usable temporary filename found")
Guido van Rossumca549821997-08-12 18:00:12 +0000348
Guido van Rossum0e548712002-08-09 16:14:33 +0000349class _TemporaryFileWrapper:
Guido van Rossumca549821997-08-12 18:00:12 +0000350 """Temporary file wrapper
351
Guido van Rossum0e548712002-08-09 16:14:33 +0000352 This class provides a wrapper around files opened for
353 temporary use. In particular, it seeks to automatically
354 remove the file when it is no longer needed.
Guido van Rossumca549821997-08-12 18:00:12 +0000355 """
Tim Petersa255a722001-12-18 22:32:40 +0000356
Guido van Rossum0e548712002-08-09 16:14:33 +0000357 def __init__(self, file, name):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000358 self.file = file
Guido van Rossum0e548712002-08-09 16:14:33 +0000359 self.name = name
Tim Petersc57a2852001-10-29 21:46:08 +0000360 self.close_called = 0
Guido van Rossumca549821997-08-12 18:00:12 +0000361
Guido van Rossumca549821997-08-12 18:00:12 +0000362 def __getattr__(self, name):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000363 file = self.__dict__['file']
364 a = getattr(file, name)
Guido van Rossum6b708d51999-06-01 18:55:36 +0000365 if type(a) != type(0):
366 setattr(self, name, a)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000367 return a
Guido van Rossumca549821997-08-12 18:00:12 +0000368
Guido van Rossum0e548712002-08-09 16:14:33 +0000369 # NT provides delete-on-close as a primitive, so we don't need
370 # the wrapper to do anything special. We still use it so that
371 # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
372 if _os.name != 'nt':
Guido van Rossumca549821997-08-12 18:00:12 +0000373
Guido van Rossum0e548712002-08-09 16:14:33 +0000374 # Cache the unlinker so we don't get spurious errors at
375 # shutdown when the module-level "os" is None'd out. Note
376 # that this must be referenced as self.unlink, because the
377 # name TemporaryFileWrapper may also get None'd out before
378 # __del__ is called.
379 unlink = _os.unlink
Tim Peters1baa22a2001-01-12 10:02:46 +0000380
Guido van Rossum0e548712002-08-09 16:14:33 +0000381 def close(self):
382 if not self.close_called:
383 self.close_called = 1
384 self.file.close()
385 self.unlink(self.name)
Tim Peters1baa22a2001-01-12 10:02:46 +0000386
Guido van Rossum0e548712002-08-09 16:14:33 +0000387 def __del__(self):
388 self.close()
Tim Peters1baa22a2001-01-12 10:02:46 +0000389
Guido van Rossum0e548712002-08-09 16:14:33 +0000390def NamedTemporaryFile(mode='w+b', bufsize=-1, suffix="",
391 prefix=template, dir=gettempdir()):
392 """Create and return a temporary file.
393 Arguments:
394 'prefix', 'suffix', 'dir' -- as for mkstemp.
395 'mode' -- the mode argument to os.fdopen (default "w+b").
396 'bufsize' -- the buffer size argument to os.fdopen (default -1).
397 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000398
Guido van Rossum0e548712002-08-09 16:14:33 +0000399 Returns a file object; the name of the file is accessible as
400 file.name. The file will be automatically deleted when it is
401 closed.
402 """
Tim Peters1baa22a2001-01-12 10:02:46 +0000403
Guido van Rossum0e548712002-08-09 16:14:33 +0000404 bin = 'b' in mode
405 if bin: flags = _bin_openflags
406 else: flags = _text_openflags
Tim Peters1baa22a2001-01-12 10:02:46 +0000407
Guido van Rossum0e548712002-08-09 16:14:33 +0000408 # Setting O_TEMPORARY in the flags causes the OS to delete
409 # the file when it is closed. This is only supported by Windows.
410 if _os.name == 'nt':
411 flags |= _os.O_TEMPORARY
Tim Peters1baa22a2001-01-12 10:02:46 +0000412
Guido van Rossum0e548712002-08-09 16:14:33 +0000413 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
414 file = _os.fdopen(fd, mode, bufsize)
415 return _TemporaryFileWrapper(file, name)
416
417if _os.name != 'posix':
418 # On non-POSIX systems, assume that we cannot unlink a file while
419 # it is open.
420 TemporaryFile = NamedTemporaryFile
Tim Peters1baa22a2001-01-12 10:02:46 +0000421
422else:
Guido van Rossum0e548712002-08-09 16:14:33 +0000423 def TemporaryFile(mode='w+b', bufsize=-1, suffix="",
424 prefix=template, dir=gettempdir()):
425 """Create and return a temporary file.
426 Arguments:
427 'prefix', 'suffix', 'directory' -- as for mkstemp.
428 'mode' -- the mode argument to os.fdopen (default "w+b").
429 'bufsize' -- the buffer size argument to os.fdopen (default -1).
430 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000431
Guido van Rossum0e548712002-08-09 16:14:33 +0000432 Returns a file object. The file has no name, and will cease to
433 exist when it is closed.
434 """
435
436 bin = 'b' in mode
437 if bin: flags = _bin_openflags
438 else: flags = _text_openflags
439
440 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
441 try:
442 _os.unlink(name)
443 return _os.fdopen(fd, mode, bufsize)
444 except:
445 _os.close(fd)
446 raise