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 |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 22 | "SpooledTemporaryFile", |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 23 | "mkstemp", "mkdtemp", # low level safe interfaces |
| 24 | "mktemp", # deprecated unsafe interface |
| 25 | "TMP_MAX", "gettempprefix", # constants |
| 26 | "tempdir", "gettempdir" |
| 27 | ] |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 28 | |
Tim Peters | 4fd5a06 | 2002-01-28 23:11:23 +0000 | [diff] [blame] | 29 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 30 | # Imports. |
Tim Peters | 4fd5a06 | 2002-01-28 23:11:23 +0000 | [diff] [blame] | 31 | |
Guido van Rossum | 9a63470 | 2007-07-09 10:24:45 +0000 | [diff] [blame] | 32 | import io as _io |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 33 | import os as _os |
| 34 | import errno as _errno |
| 35 | from random import Random as _Random |
| 36 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 37 | try: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 38 | import fcntl as _fcntl |
Tim Peters | 90ee7eb | 2004-07-18 23:58:17 +0000 | [diff] [blame] | 39 | except ImportError: |
Tim Peters | 291f14e | 2003-07-22 02:50:01 +0000 | [diff] [blame] | 40 | def _set_cloexec(fd): |
| 41 | pass |
| 42 | else: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 43 | def _set_cloexec(fd): |
Tim Peters | 90ee7eb | 2004-07-18 23:58:17 +0000 | [diff] [blame] | 44 | try: |
| 45 | flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0) |
| 46 | except IOError: |
| 47 | pass |
Alex Martelli | f09994e | 2003-11-09 16:44:09 +0000 | [diff] [blame] | 48 | else: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 49 | # flags read successfully, modify |
| 50 | flags |= _fcntl.FD_CLOEXEC |
| 51 | _fcntl.fcntl(fd, _fcntl.F_SETFD, flags) |
Tim Peters | 291f14e | 2003-07-22 02:50:01 +0000 | [diff] [blame] | 52 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 53 | |
| 54 | try: |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 55 | import _thread |
Guido van Rossum | a093424 | 2002-12-30 22:36:09 +0000 | [diff] [blame] | 56 | except ImportError: |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 57 | import _dummy_thread as _thread |
Guido van Rossum | a093424 | 2002-12-30 22:36:09 +0000 | [diff] [blame] | 58 | _allocate_lock = _thread.allocate_lock |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 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 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 77 | # Internal routines. |
| 78 | |
| 79 | _once_lock = _allocate_lock() |
| 80 | |
Guido van Rossum | b25615939 | 2003-11-10 02:16:36 +0000 | [diff] [blame] | 81 | if hasattr(_os, "lstat"): |
| 82 | _stat = _os.lstat |
| 83 | elif hasattr(_os, "stat"): |
| 84 | _stat = _os.stat |
| 85 | else: |
| 86 | # Fallback. All we need is something that raises os.error if the |
| 87 | # file doesn't exist. |
| 88 | def _stat(fn): |
| 89 | try: |
| 90 | f = open(fn) |
| 91 | except IOError: |
| 92 | raise _os.error |
| 93 | f.close() |
| 94 | |
| 95 | def _exists(fn): |
| 96 | try: |
| 97 | _stat(fn) |
| 98 | except _os.error: |
| 99 | return False |
| 100 | else: |
| 101 | return True |
| 102 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 103 | class _RandomNameSequence: |
| 104 | """An instance of _RandomNameSequence generates an endless |
| 105 | sequence of unpredictable strings which can safely be incorporated |
| 106 | into file names. Each string is six characters long. Multiple |
| 107 | threads can safely use the same instance at the same time. |
| 108 | |
| 109 | _RandomNameSequence is an iterator.""" |
| 110 | |
Tim Peters | 97701b5 | 2002-11-21 15:59:59 +0000 | [diff] [blame] | 111 | characters = ("abcdefghijklmnopqrstuvwxyz" + |
| 112 | "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 113 | "0123456789_") |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 114 | |
| 115 | def __init__(self): |
| 116 | self.mutex = _allocate_lock() |
| 117 | self.rng = _Random() |
| 118 | self.normcase = _os.path.normcase |
Tim Peters | 97701b5 | 2002-11-21 15:59:59 +0000 | [diff] [blame] | 119 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 120 | def __iter__(self): |
| 121 | return self |
| 122 | |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 123 | def __next__(self): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 124 | m = self.mutex |
| 125 | c = self.characters |
Tim Peters | 97701b5 | 2002-11-21 15:59:59 +0000 | [diff] [blame] | 126 | choose = self.rng.choice |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 127 | |
Tim Peters | 97701b5 | 2002-11-21 15:59:59 +0000 | [diff] [blame] | 128 | m.acquire() |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 129 | try: |
Tim Peters | 97701b5 | 2002-11-21 15:59:59 +0000 | [diff] [blame] | 130 | letters = [choose(c) for dummy in "123456"] |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 131 | finally: |
| 132 | m.release() |
| 133 | |
Tim Peters | 97701b5 | 2002-11-21 15:59:59 +0000 | [diff] [blame] | 134 | return self.normcase(''.join(letters)) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 135 | |
| 136 | def _candidate_tempdir_list(): |
| 137 | """Generate a list of candidate temporary directories which |
| 138 | _get_default_tempdir will try.""" |
| 139 | |
| 140 | dirlist = [] |
| 141 | |
| 142 | # First, try the environment. |
| 143 | for envname in 'TMPDIR', 'TEMP', 'TMP': |
| 144 | dirname = _os.getenv(envname) |
| 145 | if dirname: dirlist.append(dirname) |
| 146 | |
| 147 | # Failing that, try OS-specific locations. |
Alexandre Vassalotti | eca20b6 | 2008-05-16 02:54:33 +0000 | [diff] [blame] | 148 | if _os.name == 'nt': |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 149 | dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ]) |
| 150 | else: |
| 151 | dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ]) |
| 152 | |
| 153 | # As a last resort, the current directory. |
| 154 | try: |
| 155 | dirlist.append(_os.getcwd()) |
| 156 | except (AttributeError, _os.error): |
| 157 | dirlist.append(_os.curdir) |
| 158 | |
| 159 | return dirlist |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 160 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 161 | def _get_default_tempdir(): |
| 162 | """Calculate the default directory to use for temporary files. |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 163 | This routine should be called exactly once. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 164 | |
| 165 | We determine whether or not a candidate temp dir is usable by |
| 166 | trying to create and write to a file in that directory. If this |
| 167 | is successful, the test file is deleted. To prevent denial of |
| 168 | service, the name of the test file must be randomized.""" |
| 169 | |
| 170 | namer = _RandomNameSequence() |
| 171 | dirlist = _candidate_tempdir_list() |
| 172 | flags = _text_openflags |
| 173 | |
| 174 | for dir in dirlist: |
| 175 | if dir != _os.curdir: |
| 176 | dir = _os.path.normcase(_os.path.abspath(dir)) |
| 177 | # Try only a few names per directory. |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 178 | for seq in range(100): |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 179 | name = next(namer) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 180 | filename = _os.path.join(dir, name) |
| 181 | try: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 182 | fd = _os.open(filename, flags, 0o600) |
Guido van Rossum | 5424df2 | 2007-08-13 19:06:38 +0000 | [diff] [blame] | 183 | fp = _io.open(fd, 'wb') |
| 184 | fp.write(b'blat') |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 185 | fp.close() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 186 | _os.unlink(filename) |
| 187 | del fp, fd |
| 188 | return dir |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 189 | except (OSError, IOError) as e: |
Georg Brandl | 7816e51 | 2007-10-22 12:42:46 +0000 | [diff] [blame] | 190 | if e.args[0] != _errno.EEXIST: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 191 | break # no point trying more names in this directory |
| 192 | pass |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 193 | raise IOError(_errno.ENOENT, |
| 194 | "No usable temporary directory found in %s" % dirlist) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 195 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 196 | _name_sequence = None |
| 197 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 198 | def _get_candidate_names(): |
| 199 | """Common setup sequence for all user-callable interfaces.""" |
| 200 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 201 | global _name_sequence |
| 202 | if _name_sequence is None: |
| 203 | _once_lock.acquire() |
| 204 | try: |
| 205 | if _name_sequence is None: |
| 206 | _name_sequence = _RandomNameSequence() |
| 207 | finally: |
| 208 | _once_lock.release() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 209 | return _name_sequence |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 210 | |
| 211 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 212 | def _mkstemp_inner(dir, pre, suf, flags): |
| 213 | """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.""" |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 214 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 215 | names = _get_candidate_names() |
| 216 | |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 217 | for seq in range(TMP_MAX): |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 218 | name = next(names) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 219 | file = _os.path.join(dir, pre + name + suf) |
| 220 | try: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 221 | fd = _os.open(file, flags, 0o600) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 222 | _set_cloexec(fd) |
Martin v. Löwis | d662548 | 2003-10-12 17:37:01 +0000 | [diff] [blame] | 223 | return (fd, _os.path.abspath(file)) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 224 | except OSError as e: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 225 | if e.errno == _errno.EEXIST: |
| 226 | continue # try again |
| 227 | raise |
| 228 | |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 229 | raise IOError(_errno.EEXIST, "No usable temporary file name found") |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 230 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 231 | |
| 232 | # User visible interfaces. |
Guido van Rossum | b0e5718 | 1998-10-14 20:27:05 +0000 | [diff] [blame] | 233 | |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 234 | def gettempprefix(): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 235 | """Accessor for tempdir.template.""" |
| 236 | return template |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 237 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 238 | tempdir = None |
| 239 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 240 | def gettempdir(): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 241 | """Accessor for tempfile.tempdir.""" |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 242 | global tempdir |
| 243 | if tempdir is None: |
| 244 | _once_lock.acquire() |
| 245 | try: |
| 246 | if tempdir is None: |
| 247 | tempdir = _get_default_tempdir() |
| 248 | finally: |
| 249 | _once_lock.release() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 250 | return tempdir |
| 251 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 252 | def mkstemp(suffix="", prefix=template, dir=None, text=False): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 253 | """User-callable function to create and return a unique temporary |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 254 | file. The return value is a pair (fd, name) where fd is the |
| 255 | file descriptor returned by os.open, and name is the filename. |
| 256 | |
| 257 | If 'suffix' is specified, the file name will end with that suffix, |
| 258 | otherwise there will be no suffix. |
| 259 | |
| 260 | If 'prefix' is specified, the file name will begin with that prefix, |
| 261 | otherwise a default prefix is used. |
| 262 | |
| 263 | If 'dir' is specified, the file will be created in that directory, |
| 264 | otherwise a default directory is used. |
| 265 | |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 266 | If 'text' is specified and true, the file is opened in text |
| 267 | mode. Else (the default) the file is opened in binary mode. On |
| 268 | some operating systems, this makes no difference. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 269 | |
| 270 | The file is readable and writable only by the creating user ID. |
| 271 | If the operating system uses permission bits to indicate whether a |
| 272 | file is executable, the file is executable by no one. The file |
| 273 | descriptor is not inherited by children of this process. |
| 274 | |
| 275 | Caller is responsible for deleting the file when done with it. |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 276 | """ |
| 277 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 278 | if dir is None: |
| 279 | dir = gettempdir() |
| 280 | |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 281 | if text: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 282 | flags = _text_openflags |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 283 | else: |
| 284 | flags = _bin_openflags |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 285 | |
| 286 | return _mkstemp_inner(dir, prefix, suffix, flags) |
Guido van Rossum | cff3454 | 1992-01-14 18:31:56 +0000 | [diff] [blame] | 287 | |
Guido van Rossum | eee9498 | 1991-11-12 15:38:08 +0000 | [diff] [blame] | 288 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 289 | def mkdtemp(suffix="", prefix=template, dir=None): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 290 | """User-callable function to create and return a unique temporary |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 291 | directory. The return value is the pathname of the directory. |
| 292 | |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 293 | Arguments are as for mkstemp, except that the 'text' argument is |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 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 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 302 | if dir is None: |
| 303 | dir = gettempdir() |
| 304 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 305 | names = _get_candidate_names() |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 306 | |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 307 | for seq in range(TMP_MAX): |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 308 | name = next(names) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 309 | file = _os.path.join(dir, prefix + name + suffix) |
| 310 | try: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 311 | _os.mkdir(file, 0o700) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 312 | return file |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 313 | except OSError as e: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 314 | if e.errno == _errno.EEXIST: |
| 315 | continue # try again |
| 316 | raise |
| 317 | |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 318 | raise IOError(_errno.EEXIST, "No usable temporary directory name found") |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 319 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 320 | def mktemp(suffix="", prefix=template, dir=None): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 321 | """User-callable function to return a unique temporary file name. The |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 322 | file is not created. |
| 323 | |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 324 | Arguments are as for mkstemp, except that the 'text' argument is |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 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 | |
Guido van Rossum | 44f602d | 2002-11-22 15:56:29 +0000 | [diff] [blame] | 333 | ## from warnings import warn as _warn |
| 334 | ## _warn("mktemp is a potential security risk to your program", |
| 335 | ## RuntimeWarning, stacklevel=2) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 336 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 337 | if dir is None: |
| 338 | dir = gettempdir() |
| 339 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 340 | names = _get_candidate_names() |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 341 | for seq in range(TMP_MAX): |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 342 | name = next(names) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 343 | file = _os.path.join(dir, prefix + name + suffix) |
Guido van Rossum | b25615939 | 2003-11-10 02:16:36 +0000 | [diff] [blame] | 344 | if not _exists(file): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 345 | return file |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 346 | |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 347 | raise IOError(_errno.EEXIST, "No usable temporary filename found") |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 348 | |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 349 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 350 | class _TemporaryFileWrapper: |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 351 | """Temporary file wrapper |
| 352 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 353 | This class provides a wrapper around files opened for |
| 354 | temporary use. In particular, it seeks to automatically |
| 355 | remove the file when it is no longer needed. |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 356 | """ |
Tim Peters | a255a72 | 2001-12-18 22:32:40 +0000 | [diff] [blame] | 357 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 358 | def __init__(self, file, name, delete=True): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 359 | self.file = file |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 360 | self.name = name |
Tim Peters | 6ef966e | 2002-11-21 15:48:33 +0000 | [diff] [blame] | 361 | self.close_called = False |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 362 | self.delete = delete |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 363 | |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 364 | def __getattr__(self, name): |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 365 | # Attribute lookups are delegated to the underlying file |
| 366 | # and cached for non-numeric results |
| 367 | # (i.e. methods are cached, closed and friends are not) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 368 | file = self.__dict__['file'] |
| 369 | a = getattr(file, name) |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 370 | if not isinstance(a, int): |
Guido van Rossum | 6b708d5 | 1999-06-01 18:55:36 +0000 | [diff] [blame] | 371 | setattr(self, name, a) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 372 | return a |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 373 | |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 374 | # The underlying __enter__ method returns the wrong object |
| 375 | # (self.file) so override it to return the wrapper |
| 376 | def __enter__(self): |
| 377 | self.file.__enter__() |
| 378 | return self |
| 379 | |
Christian Heimes | 36d1f8e | 2008-02-28 22:21:11 +0000 | [diff] [blame] | 380 | # iter() doesn't use __getattr__ to find the __iter__ method |
Christian Heimes | c83b629 | 2008-02-28 21:10:17 +0000 | [diff] [blame] | 381 | def __iter__(self): |
Christian Heimes | 36d1f8e | 2008-02-28 22:21:11 +0000 | [diff] [blame] | 382 | return iter(self.file) |
Christian Heimes | c83b629 | 2008-02-28 21:10:17 +0000 | [diff] [blame] | 383 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 384 | # NT provides delete-on-close as a primitive, so we don't need |
| 385 | # the wrapper to do anything special. We still use it so that |
| 386 | # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile. |
| 387 | if _os.name != 'nt': |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 388 | # Cache the unlinker so we don't get spurious errors at |
| 389 | # shutdown when the module-level "os" is None'd out. Note |
| 390 | # that this must be referenced as self.unlink, because the |
| 391 | # name TemporaryFileWrapper may also get None'd out before |
| 392 | # __del__ is called. |
| 393 | unlink = _os.unlink |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 394 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 395 | def close(self): |
| 396 | if not self.close_called: |
Tim Peters | 6ef966e | 2002-11-21 15:48:33 +0000 | [diff] [blame] | 397 | self.close_called = True |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 398 | self.file.close() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 399 | if self.delete: |
| 400 | self.unlink(self.name) |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 401 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 402 | def __del__(self): |
| 403 | self.close() |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 404 | |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 405 | # Need to trap __exit__ as well to ensure the file gets |
| 406 | # deleted when used in a with statement |
| 407 | def __exit__(self, exc, value, tb): |
| 408 | result = self.file.__exit__(exc, value, tb) |
| 409 | self.close() |
| 410 | return result |
Benjamin Peterson | 98d23f2 | 2009-06-30 22:27:25 +0000 | [diff] [blame] | 411 | else: |
| 412 | def __exit__(self, exc, value, tb): |
Benjamin Peterson | 3f5de13 | 2009-07-01 15:47:07 +0000 | [diff] [blame] | 413 | self.file.__exit__(exc, value, tb) |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 414 | |
| 415 | |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 416 | def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, |
| 417 | newline=None, suffix="", prefix=template, |
| 418 | dir=None, delete=True): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 419 | """Create and return a temporary file. |
| 420 | Arguments: |
| 421 | 'prefix', 'suffix', 'dir' -- as for mkstemp. |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 422 | 'mode' -- the mode argument to io.open (default "w+b"). |
| 423 | 'buffering' -- the buffer size argument to io.open (default -1). |
| 424 | 'encoding' -- the encoding argument to io.open (default None) |
| 425 | 'newline' -- the newline argument to io.open (default None) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 426 | 'delete' -- whether the file is deleted on close (default True). |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 427 | The file is created as mkstemp() would do it. |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 428 | |
Raymond Hettinger | faa10eb | 2005-01-11 15:33:03 +0000 | [diff] [blame] | 429 | Returns an object with a file-like interface; the name of the file |
| 430 | is accessible as file.name. The file will be automatically deleted |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 431 | when it is closed unless the 'delete' argument is set to False. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 432 | """ |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 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 |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 441 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 442 | # Setting O_TEMPORARY in the flags causes the OS to delete |
| 443 | # the file when it is closed. This is only supported by Windows. |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 444 | if _os.name == 'nt' and delete: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 445 | flags |= _os.O_TEMPORARY |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 446 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 447 | (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags) |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 448 | file = _io.open(fd, mode, buffering=buffering, |
| 449 | newline=newline, encoding=encoding) |
| 450 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 451 | return _TemporaryFileWrapper(file, name, delete) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 452 | |
Jason Tishler | 80c02af | 2002-08-14 15:10:09 +0000 | [diff] [blame] | 453 | if _os.name != 'posix' or _os.sys.platform == 'cygwin': |
| 454 | # On non-POSIX and Cygwin systems, assume that we cannot unlink a file |
| 455 | # while it is open. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 456 | TemporaryFile = NamedTemporaryFile |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 457 | |
| 458 | else: |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 459 | def TemporaryFile(mode='w+b', buffering=-1, encoding=None, |
| 460 | newline=None, suffix="", prefix=template, |
| 461 | dir=None): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 462 | """Create and return a temporary file. |
| 463 | Arguments: |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 464 | 'prefix', 'suffix', 'dir' -- as for mkstemp. |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 465 | 'mode' -- the mode argument to io.open (default "w+b"). |
| 466 | 'buffering' -- the buffer size argument to io.open (default -1). |
| 467 | 'encoding' -- the encoding argument to io.open (default None) |
| 468 | 'newline' -- the newline argument to io.open (default None) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 469 | The file is created as mkstemp() would do it. |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 470 | |
Raymond Hettinger | faa10eb | 2005-01-11 15:33:03 +0000 | [diff] [blame] | 471 | Returns an object with a file-like interface. The file has no |
| 472 | name, and will cease to exist when it is closed. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 473 | """ |
| 474 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 475 | if dir is None: |
| 476 | dir = gettempdir() |
| 477 | |
Tim Peters | c21ea74 | 2002-08-13 23:36:01 +0000 | [diff] [blame] | 478 | if 'b' in mode: |
| 479 | flags = _bin_openflags |
| 480 | else: |
| 481 | flags = _text_openflags |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 482 | |
| 483 | (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags) |
| 484 | try: |
| 485 | _os.unlink(name) |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 486 | return _io.open(fd, mode, buffering=buffering, |
| 487 | newline=newline, encoding=encoding) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 488 | except: |
| 489 | _os.close(fd) |
| 490 | raise |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 491 | |
| 492 | class SpooledTemporaryFile: |
| 493 | """Temporary file wrapper, specialized to switch from |
| 494 | StringIO to a real file when it exceeds a certain size or |
| 495 | when a fileno is needed. |
| 496 | """ |
| 497 | _rolled = False |
| 498 | |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 499 | def __init__(self, max_size=0, mode='w+b', buffering=-1, |
| 500 | encoding=None, newline=None, |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 501 | suffix="", prefix=template, dir=None): |
Guido van Rossum | 9a63470 | 2007-07-09 10:24:45 +0000 | [diff] [blame] | 502 | if 'b' in mode: |
| 503 | self._file = _io.BytesIO() |
| 504 | else: |
Guido van Rossum | 5d21255 | 2007-10-29 16:42:51 +0000 | [diff] [blame] | 505 | # Setting newline="\n" avoids newline translation; |
| 506 | # this is important because otherwise on Windows we'd |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 507 | # hget double newline translation upon rollover(). |
Alexandre Vassalotti | 3ade6f9 | 2008-06-12 01:13:54 +0000 | [diff] [blame] | 508 | self._file = _io.StringIO(newline="\n") |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 509 | self._max_size = max_size |
| 510 | self._rolled = False |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 511 | self._TemporaryFileArgs = {'mode': mode, 'buffering': buffering, |
| 512 | 'suffix': suffix, 'prefix': prefix, |
| 513 | 'encoding': encoding, 'newline': newline, |
| 514 | 'dir': dir} |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 515 | |
| 516 | def _check(self, file): |
| 517 | if self._rolled: return |
| 518 | max_size = self._max_size |
| 519 | if max_size and file.tell() > max_size: |
| 520 | self.rollover() |
| 521 | |
| 522 | def rollover(self): |
| 523 | if self._rolled: return |
| 524 | file = self._file |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 525 | newfile = self._file = TemporaryFile(**self._TemporaryFileArgs) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 526 | del self._TemporaryFileArgs |
| 527 | |
| 528 | newfile.write(file.getvalue()) |
| 529 | newfile.seek(file.tell(), 0) |
| 530 | |
| 531 | self._rolled = True |
| 532 | |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 533 | # The method caching trick from NamedTemporaryFile |
| 534 | # won't work here, because _file may change from a |
| 535 | # _StringIO instance to a real file. So we list |
| 536 | # all the methods directly. |
| 537 | |
| 538 | # Context management protocol |
| 539 | def __enter__(self): |
| 540 | if self._file.closed: |
| 541 | raise ValueError("Cannot enter context with closed file") |
| 542 | return self |
| 543 | |
| 544 | def __exit__(self, exc, value, tb): |
| 545 | self._file.close() |
| 546 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 547 | # file protocol |
| 548 | def __iter__(self): |
| 549 | return self._file.__iter__() |
| 550 | |
| 551 | def close(self): |
| 552 | self._file.close() |
| 553 | |
| 554 | @property |
| 555 | def closed(self): |
| 556 | return self._file.closed |
| 557 | |
| 558 | @property |
| 559 | def encoding(self): |
| 560 | return self._file.encoding |
| 561 | |
| 562 | def fileno(self): |
| 563 | self.rollover() |
| 564 | return self._file.fileno() |
| 565 | |
| 566 | def flush(self): |
| 567 | self._file.flush() |
| 568 | |
| 569 | def isatty(self): |
| 570 | return self._file.isatty() |
| 571 | |
| 572 | @property |
| 573 | def mode(self): |
| 574 | return self._file.mode |
| 575 | |
| 576 | @property |
| 577 | def name(self): |
| 578 | return self._file.name |
| 579 | |
| 580 | @property |
| 581 | def newlines(self): |
| 582 | return self._file.newlines |
| 583 | |
| 584 | def next(self): |
| 585 | return self._file.next |
| 586 | |
| 587 | def read(self, *args): |
| 588 | return self._file.read(*args) |
| 589 | |
| 590 | def readline(self, *args): |
| 591 | return self._file.readline(*args) |
| 592 | |
| 593 | def readlines(self, *args): |
| 594 | return self._file.readlines(*args) |
| 595 | |
| 596 | def seek(self, *args): |
| 597 | self._file.seek(*args) |
| 598 | |
| 599 | @property |
| 600 | def softspace(self): |
| 601 | return self._file.softspace |
| 602 | |
| 603 | def tell(self): |
| 604 | return self._file.tell() |
| 605 | |
| 606 | def truncate(self): |
| 607 | self._file.truncate() |
| 608 | |
| 609 | def write(self, s): |
| 610 | file = self._file |
| 611 | rv = file.write(s) |
| 612 | self._check(file) |
| 613 | return rv |
| 614 | |
| 615 | def writelines(self, iterable): |
| 616 | file = self._file |
| 617 | rv = file.writelines(iterable) |
| 618 | self._check(file) |
| 619 | return rv |
| 620 | |
| 621 | def xreadlines(self, *args): |
| 622 | return self._file.xreadlines(*args) |