Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 1 | """Temporary files. |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 2 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 3 | This module provides generic, low- and high-level interfaces for |
| 4 | creating temporary files and directories. The interfaces listed |
| 5 | as "safe" just below can be used without fear of race conditions. |
| 6 | Those listed as "unsafe" cannot, and are provided for backward |
| 7 | compatibility only. |
Guido van Rossum | eee9498 | 1991-11-12 15:38:08 +0000 | [diff] [blame] | 8 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 9 | This module also provides some data items to the user: |
Guido van Rossum | eee9498 | 1991-11-12 15:38:08 +0000 | [diff] [blame] | 10 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 11 | 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 Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 19 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 20 | __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 Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 27 | |
Tim Peters | 4fd5a06 | 2002-01-28 23:11:23 +0000 | [diff] [blame] | 28 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 29 | # Imports. |
Tim Peters | 4fd5a06 | 2002-01-28 23:11:23 +0000 | [diff] [blame] | 30 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 31 | import os as _os |
| 32 | import errno as _errno |
| 33 | from random import Random as _Random |
| 34 | |
| 35 | if _os.name == 'mac': |
| 36 | import macfs as _macfs |
| 37 | import MACFS as _MACFS |
| 38 | |
| 39 | try: |
| 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) |
| 47 | except (ImportError, AttributeError): |
| 48 | def _set_cloexec(fd): |
| 49 | pass |
| 50 | |
| 51 | try: |
| 52 | import thread as _thread |
| 53 | _allocate_lock = _thread.allocate_lock |
| 54 | except (ImportError, AttributeError): |
| 55 | class _allocate_lock: |
| 56 | def acquire(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 57 | pass |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 58 | release = acquire |
| 59 | |
| 60 | _text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 61 | if hasattr(_os, 'O_NOINHERIT'): |
| 62 | _text_openflags |= _os.O_NOINHERIT |
| 63 | if hasattr(_os, 'O_NOFOLLOW'): |
| 64 | _text_openflags |= _os.O_NOFOLLOW |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 65 | |
| 66 | _bin_openflags = _text_openflags |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 67 | if hasattr(_os, 'O_BINARY'): |
| 68 | _bin_openflags |= _os.O_BINARY |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 69 | |
| 70 | if hasattr(_os, 'TMP_MAX'): |
| 71 | TMP_MAX = _os.TMP_MAX |
| 72 | else: |
| 73 | TMP_MAX = 10000 |
| 74 | |
Tim Peters | bd7b4c7 | 2002-08-13 23:33:56 +0000 | [diff] [blame] | 75 | template = "tmp" |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 76 | |
| 77 | tempdir = None |
| 78 | |
| 79 | # Internal routines. |
| 80 | |
| 81 | _once_lock = _allocate_lock() |
| 82 | |
| 83 | def _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() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 98 | # Check first outside the lock. |
Tim Peters | fd0f0c9 | 2002-08-13 23:29:21 +0000 | [diff] [blame] | 99 | if vars.get(var) is not None: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 100 | return |
| 101 | try: |
Tim Peters | 1749b25 | 2002-08-13 23:31:02 +0000 | [diff] [blame] | 102 | _once_lock.acquire() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 103 | # Check again inside the lock. |
Tim Peters | fd0f0c9 | 2002-08-13 23:29:21 +0000 | [diff] [blame] | 104 | if vars.get(var) is not None: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 105 | return |
| 106 | vars[var] = initializer() |
| 107 | finally: |
Tim Peters | 1749b25 | 2002-08-13 23:31:02 +0000 | [diff] [blame] | 108 | _once_lock.release() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 109 | |
| 110 | class _RandomNameSequence: |
| 111 | """An instance of _RandomNameSequence generates an endless |
| 112 | sequence of unpredictable strings which can safely be incorporated |
| 113 | into file names. Each string is six characters long. Multiple |
| 114 | threads can safely use the same instance at the same time. |
| 115 | |
| 116 | _RandomNameSequence is an iterator.""" |
| 117 | |
| 118 | characters = ( "abcdefghijklmnopqrstuvwxyz" |
| 119 | + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" |
| 120 | + "0123456789-_") |
| 121 | |
| 122 | def __init__(self): |
| 123 | self.mutex = _allocate_lock() |
| 124 | self.rng = _Random() |
| 125 | self.normcase = _os.path.normcase |
| 126 | def __iter__(self): |
| 127 | return self |
| 128 | |
| 129 | def next(self): |
| 130 | m = self.mutex |
| 131 | c = self.characters |
| 132 | r = self.rng |
| 133 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 134 | try: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 135 | m.acquire() |
| 136 | letters = ''.join([r.choice(c), r.choice(c), r.choice(c), |
| 137 | r.choice(c), r.choice(c), r.choice(c)]) |
| 138 | finally: |
| 139 | m.release() |
| 140 | |
| 141 | return self.normcase(letters) |
| 142 | |
| 143 | def _candidate_tempdir_list(): |
| 144 | """Generate a list of candidate temporary directories which |
| 145 | _get_default_tempdir will try.""" |
| 146 | |
| 147 | dirlist = [] |
| 148 | |
| 149 | # First, try the environment. |
| 150 | for envname in 'TMPDIR', 'TEMP', 'TMP': |
| 151 | dirname = _os.getenv(envname) |
| 152 | if dirname: dirlist.append(dirname) |
| 153 | |
| 154 | # Failing that, try OS-specific locations. |
| 155 | if _os.name == 'mac': |
| 156 | try: |
| 157 | refnum, dirid = _macfs.FindFolder(_MACFS.kOnSystemDisk, |
| 158 | _MACFS.kTemporaryFolderType, 1) |
| 159 | dirname = _macfs.FSSpec((refnum, dirid, '')).as_pathname() |
| 160 | dirlist.append(dirname) |
| 161 | except _macfs.error: |
| 162 | pass |
| 163 | elif _os.name == 'riscos': |
| 164 | dirname = _os.getenv('Wimp$ScrapDir') |
| 165 | if dirname: dirlist.append(dirname) |
| 166 | elif _os.name == 'nt': |
| 167 | dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ]) |
| 168 | else: |
| 169 | dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ]) |
| 170 | |
| 171 | # As a last resort, the current directory. |
| 172 | try: |
| 173 | dirlist.append(_os.getcwd()) |
| 174 | except (AttributeError, _os.error): |
| 175 | dirlist.append(_os.curdir) |
| 176 | |
| 177 | return dirlist |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 178 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 179 | def _get_default_tempdir(): |
| 180 | """Calculate the default directory to use for temporary files. |
| 181 | This routine should be called through '_once' (see above) as we |
| 182 | do not want multiple threads attempting this calculation simultaneously. |
| 183 | |
| 184 | We determine whether or not a candidate temp dir is usable by |
| 185 | trying to create and write to a file in that directory. If this |
| 186 | is successful, the test file is deleted. To prevent denial of |
| 187 | service, the name of the test file must be randomized.""" |
| 188 | |
| 189 | namer = _RandomNameSequence() |
| 190 | dirlist = _candidate_tempdir_list() |
| 191 | flags = _text_openflags |
| 192 | |
| 193 | for dir in dirlist: |
| 194 | if dir != _os.curdir: |
| 195 | dir = _os.path.normcase(_os.path.abspath(dir)) |
| 196 | # Try only a few names per directory. |
| 197 | for seq in xrange(100): |
| 198 | name = namer.next() |
| 199 | filename = _os.path.join(dir, name) |
| 200 | try: |
| 201 | fd = _os.open(filename, flags, 0600) |
| 202 | fp = _os.fdopen(fd, 'w') |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 203 | fp.write('blat') |
| 204 | fp.close() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 205 | _os.unlink(filename) |
| 206 | del fp, fd |
| 207 | return dir |
| 208 | except (OSError, IOError), e: |
| 209 | if e[0] != _errno.EEXIST: |
| 210 | break # no point trying more names in this directory |
| 211 | pass |
| 212 | raise IOError, (_errno.ENOENT, |
| 213 | ("No usable temporary directory found in %s" % dirlist)) |
| 214 | |
| 215 | def _get_candidate_names(): |
| 216 | """Common setup sequence for all user-callable interfaces.""" |
| 217 | |
| 218 | _once('_name_sequence', _RandomNameSequence) |
| 219 | return _name_sequence |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 220 | |
| 221 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 222 | def _mkstemp_inner(dir, pre, suf, flags): |
| 223 | """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.""" |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 224 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 225 | names = _get_candidate_names() |
| 226 | |
| 227 | for seq in xrange(TMP_MAX): |
| 228 | name = names.next() |
| 229 | file = _os.path.join(dir, pre + name + suf) |
| 230 | try: |
| 231 | fd = _os.open(file, flags, 0600) |
| 232 | _set_cloexec(fd) |
| 233 | return (fd, file) |
| 234 | except OSError, e: |
| 235 | if e.errno == _errno.EEXIST: |
| 236 | continue # try again |
| 237 | raise |
| 238 | |
| 239 | raise IOError, (_errno.EEXIST, "No usable temporary file name found") |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 240 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 241 | |
| 242 | # User visible interfaces. |
Guido van Rossum | b0e5718 | 1998-10-14 20:27:05 +0000 | [diff] [blame] | 243 | |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 244 | def gettempprefix(): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 245 | """Accessor for tempdir.template.""" |
| 246 | return template |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 247 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 248 | def gettempdir(): |
| 249 | """Accessor for tempdir.tempdir.""" |
| 250 | _once('tempdir', _get_default_tempdir) |
| 251 | return tempdir |
| 252 | |
Tim Peters | f69b3e9 | 2002-08-13 23:38:30 +0000 | [diff] [blame] | 253 | def mkstemp(suffix="", prefix=template, dir=gettempdir(), binary=True): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 254 | """mkstemp([suffix, [prefix, [dir, [binary]]]]) |
| 255 | User-callable function to create and return a unique temporary |
| 256 | file. The return value is a pair (fd, name) where fd is the |
| 257 | file descriptor returned by os.open, and name is the filename. |
| 258 | |
| 259 | If 'suffix' is specified, the file name will end with that suffix, |
| 260 | otherwise there will be no suffix. |
| 261 | |
| 262 | If 'prefix' is specified, the file name will begin with that prefix, |
| 263 | otherwise a default prefix is used. |
| 264 | |
| 265 | If 'dir' is specified, the file will be created in that directory, |
| 266 | otherwise a default directory is used. |
| 267 | |
Tim Peters | d41bf34 | 2002-08-14 00:49:50 +0000 | [diff] [blame] | 268 | If 'binary' is specified and false, the file is opened in text |
| 269 | mode. Otherwise, the file is opened in binary mode. On some |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 270 | operating systems, this makes no difference. |
| 271 | |
| 272 | The file is readable and writable only by the creating user ID. |
| 273 | If the operating system uses permission bits to indicate whether a |
| 274 | file is executable, the file is executable by no one. The file |
| 275 | descriptor is not inherited by children of this process. |
| 276 | |
| 277 | Caller is responsible for deleting the file when done with it. |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 278 | """ |
| 279 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 280 | if binary: |
| 281 | flags = _bin_openflags |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 282 | else: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 283 | flags = _text_openflags |
| 284 | |
| 285 | return _mkstemp_inner(dir, prefix, suffix, flags) |
Guido van Rossum | cff3454 | 1992-01-14 18:31:56 +0000 | [diff] [blame] | 286 | |
Guido van Rossum | eee9498 | 1991-11-12 15:38:08 +0000 | [diff] [blame] | 287 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 288 | def mkdtemp(suffix="", prefix=template, dir=gettempdir()): |
| 289 | """mkdtemp([suffix, [prefix, [dir]]]) |
| 290 | User-callable function to create and return a unique temporary |
| 291 | directory. The return value is the pathname of the directory. |
| 292 | |
| 293 | Arguments are as for mkstemp, except that the 'binary' argument is |
| 294 | not accepted. |
| 295 | |
| 296 | The directory is readable, writable, and searchable only by the |
| 297 | creating user. |
| 298 | |
| 299 | Caller is responsible for deleting the directory when done with it. |
| 300 | """ |
| 301 | |
| 302 | names = _get_candidate_names() |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 303 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 304 | for seq in xrange(TMP_MAX): |
| 305 | name = names.next() |
| 306 | file = _os.path.join(dir, prefix + name + suffix) |
| 307 | try: |
| 308 | _os.mkdir(file, 0700) |
| 309 | return file |
| 310 | except OSError, e: |
| 311 | if e.errno == _errno.EEXIST: |
| 312 | continue # try again |
| 313 | raise |
| 314 | |
| 315 | raise IOError, (_errno.EEXIST, "No usable temporary directory name found") |
| 316 | |
| 317 | def mktemp(suffix="", prefix=template, dir=gettempdir()): |
| 318 | """mktemp([suffix, [prefix, [dir]]]) |
| 319 | User-callable function to return a unique temporary file name. The |
| 320 | file is not created. |
| 321 | |
| 322 | Arguments are as for mkstemp, except that the 'binary' argument is |
| 323 | not accepted. |
| 324 | |
| 325 | This function is unsafe and should not be used. The file name |
| 326 | refers to a file that did not exist at some point, but by the time |
| 327 | you get around to creating it, someone else may have beaten you to |
| 328 | the punch. |
| 329 | """ |
| 330 | |
| 331 | from warnings import warn as _warn |
| 332 | _warn("mktemp is a potential security risk to your program", |
| 333 | RuntimeWarning, stacklevel=2) |
| 334 | |
| 335 | names = _get_candidate_names() |
| 336 | for seq in xrange(TMP_MAX): |
| 337 | name = names.next() |
| 338 | file = _os.path.join(dir, prefix + name + suffix) |
| 339 | if not _os.path.exists(file): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 340 | return file |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 341 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 342 | raise IOError, (_errno.EEXIST, "No usable temporary filename found") |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 343 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 344 | class _TemporaryFileWrapper: |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 345 | """Temporary file wrapper |
| 346 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 347 | This class provides a wrapper around files opened for |
| 348 | temporary use. In particular, it seeks to automatically |
| 349 | remove the file when it is no longer needed. |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 350 | """ |
Tim Peters | a255a72 | 2001-12-18 22:32:40 +0000 | [diff] [blame] | 351 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 352 | def __init__(self, file, name): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 353 | self.file = file |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 354 | self.name = name |
Tim Peters | c57a285 | 2001-10-29 21:46:08 +0000 | [diff] [blame] | 355 | self.close_called = 0 |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 356 | |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 357 | def __getattr__(self, name): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 358 | file = self.__dict__['file'] |
| 359 | a = getattr(file, name) |
Guido van Rossum | 6b708d5 | 1999-06-01 18:55:36 +0000 | [diff] [blame] | 360 | if type(a) != type(0): |
| 361 | setattr(self, name, a) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 362 | return a |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 363 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 364 | # NT provides delete-on-close as a primitive, so we don't need |
| 365 | # the wrapper to do anything special. We still use it so that |
| 366 | # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile. |
| 367 | if _os.name != 'nt': |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 368 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 369 | # Cache the unlinker so we don't get spurious errors at |
| 370 | # shutdown when the module-level "os" is None'd out. Note |
| 371 | # that this must be referenced as self.unlink, because the |
| 372 | # name TemporaryFileWrapper may also get None'd out before |
| 373 | # __del__ is called. |
| 374 | unlink = _os.unlink |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 375 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 376 | def close(self): |
| 377 | if not self.close_called: |
| 378 | self.close_called = 1 |
| 379 | self.file.close() |
| 380 | self.unlink(self.name) |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 381 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 382 | def __del__(self): |
| 383 | self.close() |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 384 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 385 | def NamedTemporaryFile(mode='w+b', bufsize=-1, suffix="", |
| 386 | prefix=template, dir=gettempdir()): |
| 387 | """Create and return a temporary file. |
| 388 | Arguments: |
| 389 | 'prefix', 'suffix', 'dir' -- as for mkstemp. |
| 390 | 'mode' -- the mode argument to os.fdopen (default "w+b"). |
| 391 | 'bufsize' -- the buffer size argument to os.fdopen (default -1). |
| 392 | The file is created as mkstemp() would do it. |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 393 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 394 | Returns a file object; the name of the file is accessible as |
| 395 | file.name. The file will be automatically deleted when it is |
| 396 | closed. |
| 397 | """ |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 398 | |
Tim Peters | c21ea74 | 2002-08-13 23:36:01 +0000 | [diff] [blame] | 399 | if 'b' in mode: |
| 400 | flags = _bin_openflags |
| 401 | else: |
| 402 | flags = _text_openflags |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 403 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 404 | # Setting O_TEMPORARY in the flags causes the OS to delete |
| 405 | # the file when it is closed. This is only supported by Windows. |
| 406 | if _os.name == 'nt': |
| 407 | flags |= _os.O_TEMPORARY |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 408 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 409 | (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags) |
| 410 | file = _os.fdopen(fd, mode, bufsize) |
| 411 | return _TemporaryFileWrapper(file, name) |
| 412 | |
| 413 | if _os.name != 'posix': |
| 414 | # On non-POSIX systems, assume that we cannot unlink a file while |
| 415 | # it is open. |
| 416 | TemporaryFile = NamedTemporaryFile |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 417 | |
| 418 | else: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 419 | def TemporaryFile(mode='w+b', bufsize=-1, suffix="", |
| 420 | prefix=template, dir=gettempdir()): |
| 421 | """Create and return a temporary file. |
| 422 | Arguments: |
| 423 | 'prefix', 'suffix', 'directory' -- as for mkstemp. |
| 424 | 'mode' -- the mode argument to os.fdopen (default "w+b"). |
| 425 | 'bufsize' -- the buffer size argument to os.fdopen (default -1). |
| 426 | The file is created as mkstemp() would do it. |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 427 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 428 | Returns a file object. The file has no name, and will cease to |
| 429 | exist when it is closed. |
| 430 | """ |
| 431 | |
Tim Peters | c21ea74 | 2002-08-13 23:36:01 +0000 | [diff] [blame] | 432 | if 'b' in mode: |
| 433 | flags = _bin_openflags |
| 434 | else: |
| 435 | flags = _text_openflags |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 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 |