blob: 756d8c87273e765cfe3a8b07ce63c69a6682c238 [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':
Jack Jansenbb829b72003-03-21 12:55:38 +000036 import Carbon.Folder as _Folder
37 import Carbon.Folders as _Folders
Guido van Rossum0e548712002-08-09 16:14:33 +000038
39try:
40 import fcntl as _fcntl
Tim Peters291f14e2003-07-22 02:50:01 +000041 # If PYTHONCASEOK is set on Windows, stinking FCNTL.py gets
42 # imported, and we don't get an ImportError then. Provoke
43 # an AttributeError instead in that case.
44 _fcntl.fcntl
45except (ImportError, AttributeError):
46 def _set_cloexec(fd):
47 pass
48else:
Guido van Rossum0e548712002-08-09 16:14:33 +000049 def _set_cloexec(fd):
50 flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0)
51 if flags >= 0:
52 # flags read successfully, modify
53 flags |= _fcntl.FD_CLOEXEC
54 _fcntl.fcntl(fd, _fcntl.F_SETFD, flags)
Tim Peters291f14e2003-07-22 02:50:01 +000055
Guido van Rossum0e548712002-08-09 16:14:33 +000056
57try:
58 import thread as _thread
Guido van Rossuma0934242002-12-30 22:36:09 +000059except ImportError:
60 import dummy_thread as _thread
61_allocate_lock = _thread.allocate_lock
Guido van Rossum0e548712002-08-09 16:14:33 +000062
63_text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL
Tim Petersa0d55de2002-08-09 18:01:01 +000064if hasattr(_os, 'O_NOINHERIT'):
65 _text_openflags |= _os.O_NOINHERIT
66if hasattr(_os, 'O_NOFOLLOW'):
67 _text_openflags |= _os.O_NOFOLLOW
Guido van Rossum0e548712002-08-09 16:14:33 +000068
69_bin_openflags = _text_openflags
Tim Petersa0d55de2002-08-09 18:01:01 +000070if hasattr(_os, 'O_BINARY'):
71 _bin_openflags |= _os.O_BINARY
Guido van Rossum0e548712002-08-09 16:14:33 +000072
73if hasattr(_os, 'TMP_MAX'):
74 TMP_MAX = _os.TMP_MAX
75else:
76 TMP_MAX = 10000
77
Tim Petersbd7b4c72002-08-13 23:33:56 +000078template = "tmp"
Guido van Rossum0e548712002-08-09 16:14:33 +000079
80tempdir = None
81
82# Internal routines.
83
84_once_lock = _allocate_lock()
85
Guido van Rossum0e548712002-08-09 16:14:33 +000086class _RandomNameSequence:
87 """An instance of _RandomNameSequence generates an endless
88 sequence of unpredictable strings which can safely be incorporated
89 into file names. Each string is six characters long. Multiple
90 threads can safely use the same instance at the same time.
91
92 _RandomNameSequence is an iterator."""
93
Tim Peters97701b52002-11-21 15:59:59 +000094 characters = ("abcdefghijklmnopqrstuvwxyz" +
95 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
96 "0123456789-_")
Guido van Rossum0e548712002-08-09 16:14:33 +000097
98 def __init__(self):
99 self.mutex = _allocate_lock()
100 self.rng = _Random()
101 self.normcase = _os.path.normcase
Tim Peters97701b52002-11-21 15:59:59 +0000102
Guido van Rossum0e548712002-08-09 16:14:33 +0000103 def __iter__(self):
104 return self
105
106 def next(self):
107 m = self.mutex
108 c = self.characters
Tim Peters97701b52002-11-21 15:59:59 +0000109 choose = self.rng.choice
Guido van Rossum0e548712002-08-09 16:14:33 +0000110
Tim Peters97701b52002-11-21 15:59:59 +0000111 m.acquire()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000112 try:
Tim Peters97701b52002-11-21 15:59:59 +0000113 letters = [choose(c) for dummy in "123456"]
Guido van Rossum0e548712002-08-09 16:14:33 +0000114 finally:
115 m.release()
116
Tim Peters97701b52002-11-21 15:59:59 +0000117 return self.normcase(''.join(letters))
Guido van Rossum0e548712002-08-09 16:14:33 +0000118
119def _candidate_tempdir_list():
120 """Generate a list of candidate temporary directories which
121 _get_default_tempdir will try."""
122
123 dirlist = []
124
125 # First, try the environment.
126 for envname in 'TMPDIR', 'TEMP', 'TMP':
127 dirname = _os.getenv(envname)
128 if dirname: dirlist.append(dirname)
129
130 # Failing that, try OS-specific locations.
131 if _os.name == 'mac':
132 try:
Jack Jansenbb829b72003-03-21 12:55:38 +0000133 fsr = _Folder.FSFindFolder(_Folders.kOnSystemDisk,
134 _Folders.kTemporaryFolderType, 1)
135 dirname = fsr.as_pathname()
Guido van Rossum0e548712002-08-09 16:14:33 +0000136 dirlist.append(dirname)
Jack Jansenbb829b72003-03-21 12:55:38 +0000137 except _Folder.error:
Guido van Rossum0e548712002-08-09 16:14:33 +0000138 pass
139 elif _os.name == 'riscos':
140 dirname = _os.getenv('Wimp$ScrapDir')
141 if dirname: dirlist.append(dirname)
142 elif _os.name == 'nt':
143 dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
144 else:
145 dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
146
147 # As a last resort, the current directory.
148 try:
149 dirlist.append(_os.getcwd())
150 except (AttributeError, _os.error):
151 dirlist.append(_os.curdir)
152
153 return dirlist
Tim Petersa0d55de2002-08-09 18:01:01 +0000154
Guido van Rossum0e548712002-08-09 16:14:33 +0000155def _get_default_tempdir():
156 """Calculate the default directory to use for temporary files.
Guido van Rossume888cdc2002-08-17 14:50:24 +0000157 This routine should be called exactly once.
Guido van Rossum0e548712002-08-09 16:14:33 +0000158
159 We determine whether or not a candidate temp dir is usable by
160 trying to create and write to a file in that directory. If this
161 is successful, the test file is deleted. To prevent denial of
162 service, the name of the test file must be randomized."""
163
164 namer = _RandomNameSequence()
165 dirlist = _candidate_tempdir_list()
166 flags = _text_openflags
167
168 for dir in dirlist:
169 if dir != _os.curdir:
170 dir = _os.path.normcase(_os.path.abspath(dir))
171 # Try only a few names per directory.
172 for seq in xrange(100):
173 name = namer.next()
174 filename = _os.path.join(dir, name)
175 try:
176 fd = _os.open(filename, flags, 0600)
177 fp = _os.fdopen(fd, 'w')
Tim Petersb90f89a2001-01-15 03:26:36 +0000178 fp.write('blat')
179 fp.close()
Guido van Rossum0e548712002-08-09 16:14:33 +0000180 _os.unlink(filename)
181 del fp, fd
182 return dir
183 except (OSError, IOError), e:
184 if e[0] != _errno.EEXIST:
185 break # no point trying more names in this directory
186 pass
187 raise IOError, (_errno.ENOENT,
188 ("No usable temporary directory found in %s" % dirlist))
189
Guido van Rossume888cdc2002-08-17 14:50:24 +0000190_name_sequence = None
191
Guido van Rossum0e548712002-08-09 16:14:33 +0000192def _get_candidate_names():
193 """Common setup sequence for all user-callable interfaces."""
194
Guido van Rossume888cdc2002-08-17 14:50:24 +0000195 global _name_sequence
196 if _name_sequence is None:
197 _once_lock.acquire()
198 try:
199 if _name_sequence is None:
200 _name_sequence = _RandomNameSequence()
201 finally:
202 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000203 return _name_sequence
Guido van Rossum41f95031992-03-31 19:02:01 +0000204
205
Guido van Rossum0e548712002-08-09 16:14:33 +0000206def _mkstemp_inner(dir, pre, suf, flags):
207 """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
Tim Peters9fadfb02001-01-13 03:04:02 +0000208
Guido van Rossum0e548712002-08-09 16:14:33 +0000209 names = _get_candidate_names()
210
211 for seq in xrange(TMP_MAX):
212 name = names.next()
213 file = _os.path.join(dir, pre + name + suf)
214 try:
215 fd = _os.open(file, flags, 0600)
216 _set_cloexec(fd)
217 return (fd, file)
218 except OSError, e:
219 if e.errno == _errno.EEXIST:
220 continue # try again
221 raise
222
223 raise IOError, (_errno.EEXIST, "No usable temporary file name found")
Tim Petersa0d55de2002-08-09 18:01:01 +0000224
Guido van Rossum0e548712002-08-09 16:14:33 +0000225
226# User visible interfaces.
Guido van Rossumb0e57181998-10-14 20:27:05 +0000227
Guido van Rossum41f95031992-03-31 19:02:01 +0000228def gettempprefix():
Guido van Rossum0e548712002-08-09 16:14:33 +0000229 """Accessor for tempdir.template."""
230 return template
Tim Peters9fadfb02001-01-13 03:04:02 +0000231
Guido van Rossume888cdc2002-08-17 14:50:24 +0000232tempdir = None
233
Guido van Rossum0e548712002-08-09 16:14:33 +0000234def gettempdir():
235 """Accessor for tempdir.tempdir."""
Guido van Rossume888cdc2002-08-17 14:50:24 +0000236 global tempdir
237 if tempdir is None:
238 _once_lock.acquire()
239 try:
240 if tempdir is None:
241 tempdir = _get_default_tempdir()
242 finally:
243 _once_lock.release()
Guido van Rossum0e548712002-08-09 16:14:33 +0000244 return tempdir
245
Guido van Rossume888cdc2002-08-17 14:50:24 +0000246def mkstemp(suffix="", prefix=template, dir=None, text=False):
Tim Peters04490bf2002-08-14 15:41:26 +0000247 """mkstemp([suffix, [prefix, [dir, [text]]]])
Guido van Rossum0e548712002-08-09 16:14:33 +0000248 User-callable function to create and return a unique temporary
249 file. The return value is a pair (fd, name) where fd is the
250 file descriptor returned by os.open, and name is the filename.
251
252 If 'suffix' is specified, the file name will end with that suffix,
253 otherwise there will be no suffix.
254
255 If 'prefix' is specified, the file name will begin with that prefix,
256 otherwise a default prefix is used.
257
258 If 'dir' is specified, the file will be created in that directory,
259 otherwise a default directory is used.
260
Tim Peters04490bf2002-08-14 15:41:26 +0000261 If 'text' is specified and true, the file is opened in text
262 mode. Else (the default) the file is opened in binary mode. On
263 some operating systems, this makes no difference.
Guido van Rossum0e548712002-08-09 16:14:33 +0000264
265 The file is readable and writable only by the creating user ID.
266 If the operating system uses permission bits to indicate whether a
267 file is executable, the file is executable by no one. The file
268 descriptor is not inherited by children of this process.
269
270 Caller is responsible for deleting the file when done with it.
Tim Peters9fadfb02001-01-13 03:04:02 +0000271 """
272
Guido van Rossume888cdc2002-08-17 14:50:24 +0000273 if dir is None:
274 dir = gettempdir()
275
Tim Peters04490bf2002-08-14 15:41:26 +0000276 if text:
Guido van Rossum0e548712002-08-09 16:14:33 +0000277 flags = _text_openflags
Tim Peters04490bf2002-08-14 15:41:26 +0000278 else:
279 flags = _bin_openflags
Guido van Rossum0e548712002-08-09 16:14:33 +0000280
281 return _mkstemp_inner(dir, prefix, suffix, flags)
Guido van Rossumcff34541992-01-14 18:31:56 +0000282
Guido van Rossumeee94981991-11-12 15:38:08 +0000283
Guido van Rossume888cdc2002-08-17 14:50:24 +0000284def mkdtemp(suffix="", prefix=template, dir=None):
Guido van Rossum0e548712002-08-09 16:14:33 +0000285 """mkdtemp([suffix, [prefix, [dir]]])
286 User-callable function to create and return a unique temporary
287 directory. The return value is the pathname of the directory.
288
Tim Peters04490bf2002-08-14 15:41:26 +0000289 Arguments are as for mkstemp, except that the 'text' argument is
Guido van Rossum0e548712002-08-09 16:14:33 +0000290 not accepted.
291
292 The directory is readable, writable, and searchable only by the
293 creating user.
294
295 Caller is responsible for deleting the directory when done with it.
296 """
297
Guido van Rossume888cdc2002-08-17 14:50:24 +0000298 if dir is None:
299 dir = gettempdir()
300
Guido van Rossum0e548712002-08-09 16:14:33 +0000301 names = _get_candidate_names()
Tim Petersa0d55de2002-08-09 18:01:01 +0000302
Guido van Rossum0e548712002-08-09 16:14:33 +0000303 for seq in xrange(TMP_MAX):
304 name = names.next()
305 file = _os.path.join(dir, prefix + name + suffix)
306 try:
307 _os.mkdir(file, 0700)
308 return file
309 except OSError, e:
310 if e.errno == _errno.EEXIST:
311 continue # try again
312 raise
313
314 raise IOError, (_errno.EEXIST, "No usable temporary directory name found")
315
Guido van Rossume888cdc2002-08-17 14:50:24 +0000316def mktemp(suffix="", prefix=template, dir=None):
Guido van Rossum0e548712002-08-09 16:14:33 +0000317 """mktemp([suffix, [prefix, [dir]]])
318 User-callable function to return a unique temporary file name. The
319 file is not created.
320
Tim Peters04490bf2002-08-14 15:41:26 +0000321 Arguments are as for mkstemp, except that the 'text' argument is
Guido van Rossum0e548712002-08-09 16:14:33 +0000322 not accepted.
323
324 This function is unsafe and should not be used. The file name
325 refers to a file that did not exist at some point, but by the time
326 you get around to creating it, someone else may have beaten you to
327 the punch.
328 """
329
Guido van Rossum44f602d2002-11-22 15:56:29 +0000330## from warnings import warn as _warn
331## _warn("mktemp is a potential security risk to your program",
332## RuntimeWarning, stacklevel=2)
Guido van Rossum0e548712002-08-09 16:14:33 +0000333
Guido van Rossume888cdc2002-08-17 14:50:24 +0000334 if dir is None:
335 dir = gettempdir()
336
Guido van Rossum0e548712002-08-09 16:14:33 +0000337 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 Peters6ef966e2002-11-21 15:48:33 +0000357 self.close_called = False
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:
Tim Peters6ef966e2002-11-21 15:48:33 +0000380 self.close_called = True
Guido van Rossum0e548712002-08-09 16:14:33 +0000381 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="",
Guido van Rossume888cdc2002-08-17 14:50:24 +0000388 prefix=template, dir=None):
Guido van Rossum0e548712002-08-09 16:14:33 +0000389 """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 Rossume888cdc2002-08-17 14:50:24 +0000401 if dir is None:
402 dir = gettempdir()
403
Tim Petersc21ea742002-08-13 23:36:01 +0000404 if 'b' in mode:
405 flags = _bin_openflags
406 else:
407 flags = _text_openflags
Tim Peters1baa22a2001-01-12 10:02:46 +0000408
Guido van Rossum0e548712002-08-09 16:14:33 +0000409 # Setting O_TEMPORARY in the flags causes the OS to delete
410 # the file when it is closed. This is only supported by Windows.
411 if _os.name == 'nt':
412 flags |= _os.O_TEMPORARY
Tim Peters1baa22a2001-01-12 10:02:46 +0000413
Guido van Rossum0e548712002-08-09 16:14:33 +0000414 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
415 file = _os.fdopen(fd, mode, bufsize)
416 return _TemporaryFileWrapper(file, name)
417
Jason Tishler80c02af2002-08-14 15:10:09 +0000418if _os.name != 'posix' or _os.sys.platform == 'cygwin':
419 # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
420 # while it is open.
Guido van Rossum0e548712002-08-09 16:14:33 +0000421 TemporaryFile = NamedTemporaryFile
Tim Peters1baa22a2001-01-12 10:02:46 +0000422
423else:
Guido van Rossum0e548712002-08-09 16:14:33 +0000424 def TemporaryFile(mode='w+b', bufsize=-1, suffix="",
Guido van Rossume888cdc2002-08-17 14:50:24 +0000425 prefix=template, dir=None):
Guido van Rossum0e548712002-08-09 16:14:33 +0000426 """Create and return a temporary file.
427 Arguments:
428 'prefix', 'suffix', 'directory' -- as for mkstemp.
429 'mode' -- the mode argument to os.fdopen (default "w+b").
430 'bufsize' -- the buffer size argument to os.fdopen (default -1).
431 The file is created as mkstemp() would do it.
Tim Peters1baa22a2001-01-12 10:02:46 +0000432
Guido van Rossum0e548712002-08-09 16:14:33 +0000433 Returns a file object. The file has no name, and will cease to
434 exist when it is closed.
435 """
436
Guido van Rossume888cdc2002-08-17 14:50:24 +0000437 if dir is None:
438 dir = gettempdir()
439
Tim Petersc21ea742002-08-13 23:36:01 +0000440 if 'b' in mode:
441 flags = _bin_openflags
442 else:
443 flags = _text_openflags
Guido van Rossum0e548712002-08-09 16:14:33 +0000444
445 (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
446 try:
447 _os.unlink(name)
448 return _os.fdopen(fd, mode, bufsize)
449 except:
450 _os.close(fd)
451 raise