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