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 |
Yury Selivanov | 0b86660 | 2014-09-26 17:08:21 -0400 | [diff] [blame] | 4 | creating temporary files and directories. All of the interfaces |
| 5 | provided by this module can be used without fear of race conditions |
| 6 | except for 'mktemp'. 'mktemp' is subject to race conditions and |
| 7 | should not be used; it is provided for backward compatibility only. |
Guido van Rossum | eee9498 | 1991-11-12 15:38:08 +0000 | [diff] [blame] | 8 | |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 9 | The default path names are returned as str. If you supply bytes as |
| 10 | input, all return values will be in bytes. Ex: |
| 11 | |
| 12 | >>> tempfile.mkstemp() |
| 13 | (4, '/tmp/tmptpu9nin8') |
| 14 | >>> tempfile.mkdtemp(suffix=b'') |
| 15 | b'/tmp/tmppbi8f0hy' |
| 16 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 17 | This module also provides some data items to the user: |
Guido van Rossum | eee9498 | 1991-11-12 15:38:08 +0000 | [diff] [blame] | 18 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 19 | TMP_MAX - maximum number of names that will be tried before |
| 20 | giving up. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 21 | tempdir - If this is set to a string before the first use of |
| 22 | any routine from this module, it will be considered as |
| 23 | another candidate location to store temporary files. |
| 24 | """ |
Skip Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 25 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 26 | __all__ = [ |
| 27 | "NamedTemporaryFile", "TemporaryFile", # high level safe interfaces |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 28 | "SpooledTemporaryFile", "TemporaryDirectory", |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 29 | "mkstemp", "mkdtemp", # low level safe interfaces |
| 30 | "mktemp", # deprecated unsafe interface |
| 31 | "TMP_MAX", "gettempprefix", # constants |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 32 | "tempdir", "gettempdir", |
| 33 | "gettempprefixb", "gettempdirb", |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 34 | ] |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 35 | |
Tim Peters | 4fd5a06 | 2002-01-28 23:11:23 +0000 | [diff] [blame] | 36 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 37 | # Imports. |
Tim Peters | 4fd5a06 | 2002-01-28 23:11:23 +0000 | [diff] [blame] | 38 | |
Antoine Pitrou | 17c9326 | 2013-12-21 22:14:56 +0100 | [diff] [blame] | 39 | import functools as _functools |
Nick Coghlan | 6b22f3f | 2010-12-12 15:24:21 +0000 | [diff] [blame] | 40 | import warnings as _warnings |
Guido van Rossum | 9a63470 | 2007-07-09 10:24:45 +0000 | [diff] [blame] | 41 | import io as _io |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 42 | import os as _os |
Serhiy Storchaka | 99e033b | 2014-01-27 11:18:27 +0200 | [diff] [blame] | 43 | import shutil as _shutil |
Serhiy Storchaka | 7451a72 | 2013-02-09 22:25:49 +0200 | [diff] [blame] | 44 | import errno as _errno |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 45 | from random import Random as _Random |
Serhiy Storchaka | a28632b | 2014-01-27 11:21:54 +0200 | [diff] [blame] | 46 | import weakref as _weakref |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 47 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 48 | try: |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 49 | import _thread |
Brett Cannon | cd171c8 | 2013-07-04 17:43:24 -0400 | [diff] [blame] | 50 | except ImportError: |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 51 | import _dummy_thread as _thread |
Guido van Rossum | a093424 | 2002-12-30 22:36:09 +0000 | [diff] [blame] | 52 | _allocate_lock = _thread.allocate_lock |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 53 | |
| 54 | _text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 55 | if hasattr(_os, 'O_NOFOLLOW'): |
| 56 | _text_openflags |= _os.O_NOFOLLOW |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 57 | |
| 58 | _bin_openflags = _text_openflags |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 59 | if hasattr(_os, 'O_BINARY'): |
| 60 | _bin_openflags |= _os.O_BINARY |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 61 | |
| 62 | if hasattr(_os, 'TMP_MAX'): |
| 63 | TMP_MAX = _os.TMP_MAX |
| 64 | else: |
| 65 | TMP_MAX = 10000 |
| 66 | |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 67 | # This variable _was_ unused for legacy reasons, see issue 10354. |
| 68 | # But as of 3.5 we actually use it at runtime so changing it would |
| 69 | # have a possibly desirable side effect... But we do not want to support |
| 70 | # that as an API. It is undocumented on purpose. Do not depend on this. |
Tim Peters | bd7b4c7 | 2002-08-13 23:33:56 +0000 | [diff] [blame] | 71 | template = "tmp" |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 72 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 73 | # Internal routines. |
| 74 | |
| 75 | _once_lock = _allocate_lock() |
| 76 | |
Guido van Rossum | b25615939 | 2003-11-10 02:16:36 +0000 | [diff] [blame] | 77 | if hasattr(_os, "lstat"): |
| 78 | _stat = _os.lstat |
| 79 | elif hasattr(_os, "stat"): |
| 80 | _stat = _os.stat |
| 81 | else: |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 82 | # Fallback. All we need is something that raises OSError if the |
Guido van Rossum | b25615939 | 2003-11-10 02:16:36 +0000 | [diff] [blame] | 83 | # file doesn't exist. |
| 84 | def _stat(fn): |
Victor Stinner | daf4555 | 2013-08-28 00:53:59 +0200 | [diff] [blame] | 85 | fd = _os.open(fn, _os.O_RDONLY) |
Victor Stinner | 69b1e26 | 2014-03-20 08:50:52 +0100 | [diff] [blame] | 86 | _os.close(fd) |
Guido van Rossum | b25615939 | 2003-11-10 02:16:36 +0000 | [diff] [blame] | 87 | |
| 88 | def _exists(fn): |
| 89 | try: |
| 90 | _stat(fn) |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 91 | except OSError: |
Guido van Rossum | b25615939 | 2003-11-10 02:16:36 +0000 | [diff] [blame] | 92 | return False |
| 93 | else: |
| 94 | return True |
| 95 | |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 96 | |
| 97 | def _infer_return_type(*args): |
| 98 | """Look at the type of all args and divine their implied return type.""" |
| 99 | return_type = None |
| 100 | for arg in args: |
| 101 | if arg is None: |
| 102 | continue |
| 103 | if isinstance(arg, bytes): |
| 104 | if return_type is str: |
| 105 | raise TypeError("Can't mix bytes and non-bytes in " |
| 106 | "path components.") |
| 107 | return_type = bytes |
| 108 | else: |
| 109 | if return_type is bytes: |
| 110 | raise TypeError("Can't mix bytes and non-bytes in " |
| 111 | "path components.") |
| 112 | return_type = str |
| 113 | if return_type is None: |
| 114 | return str # tempfile APIs return a str by default. |
| 115 | return return_type |
| 116 | |
| 117 | |
| 118 | def _sanitize_params(prefix, suffix, dir): |
| 119 | """Common parameter processing for most APIs in this module.""" |
| 120 | output_type = _infer_return_type(prefix, suffix, dir) |
| 121 | if suffix is None: |
| 122 | suffix = output_type() |
| 123 | if prefix is None: |
| 124 | if output_type is str: |
| 125 | prefix = template |
| 126 | else: |
| 127 | prefix = _os.fsencode(template) |
| 128 | if dir is None: |
| 129 | if output_type is str: |
| 130 | dir = gettempdir() |
| 131 | else: |
| 132 | dir = gettempdirb() |
| 133 | return prefix, suffix, dir, output_type |
| 134 | |
| 135 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 136 | class _RandomNameSequence: |
| 137 | """An instance of _RandomNameSequence generates an endless |
| 138 | sequence of unpredictable strings which can safely be incorporated |
| 139 | into file names. Each string is six characters long. Multiple |
| 140 | threads can safely use the same instance at the same time. |
| 141 | |
| 142 | _RandomNameSequence is an iterator.""" |
| 143 | |
Raymond Hettinger | 572895b | 2010-11-09 03:43:58 +0000 | [diff] [blame] | 144 | characters = "abcdefghijklmnopqrstuvwxyz0123456789_" |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 145 | |
Antoine Pitrou | 4558bad | 2011-11-25 21:28:15 +0100 | [diff] [blame] | 146 | @property |
| 147 | def rng(self): |
| 148 | cur_pid = _os.getpid() |
| 149 | if cur_pid != getattr(self, '_rng_pid', None): |
| 150 | self._rng = _Random() |
| 151 | self._rng_pid = cur_pid |
| 152 | return self._rng |
Tim Peters | 97701b5 | 2002-11-21 15:59:59 +0000 | [diff] [blame] | 153 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 154 | def __iter__(self): |
| 155 | return self |
| 156 | |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 157 | def __next__(self): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 158 | c = self.characters |
Tim Peters | 97701b5 | 2002-11-21 15:59:59 +0000 | [diff] [blame] | 159 | choose = self.rng.choice |
Victor Stinner | 9786910 | 2013-08-14 01:28:28 +0200 | [diff] [blame] | 160 | letters = [choose(c) for dummy in range(8)] |
Raymond Hettinger | 572895b | 2010-11-09 03:43:58 +0000 | [diff] [blame] | 161 | return ''.join(letters) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 162 | |
| 163 | def _candidate_tempdir_list(): |
| 164 | """Generate a list of candidate temporary directories which |
| 165 | _get_default_tempdir will try.""" |
| 166 | |
| 167 | dirlist = [] |
| 168 | |
| 169 | # First, try the environment. |
| 170 | for envname in 'TMPDIR', 'TEMP', 'TMP': |
| 171 | dirname = _os.getenv(envname) |
| 172 | if dirname: dirlist.append(dirname) |
| 173 | |
| 174 | # Failing that, try OS-specific locations. |
Alexandre Vassalotti | eca20b6 | 2008-05-16 02:54:33 +0000 | [diff] [blame] | 175 | if _os.name == 'nt': |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 176 | dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ]) |
| 177 | else: |
| 178 | dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ]) |
| 179 | |
| 180 | # As a last resort, the current directory. |
| 181 | try: |
| 182 | dirlist.append(_os.getcwd()) |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 183 | except (AttributeError, OSError): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 184 | dirlist.append(_os.curdir) |
| 185 | |
| 186 | return dirlist |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 187 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 188 | def _get_default_tempdir(): |
| 189 | """Calculate the default directory to use for temporary files. |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 190 | This routine should be called exactly once. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 191 | |
| 192 | We determine whether or not a candidate temp dir is usable by |
| 193 | trying to create and write to a file in that directory. If this |
| 194 | is successful, the test file is deleted. To prevent denial of |
| 195 | service, the name of the test file must be randomized.""" |
| 196 | |
| 197 | namer = _RandomNameSequence() |
| 198 | dirlist = _candidate_tempdir_list() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 199 | |
| 200 | for dir in dirlist: |
| 201 | if dir != _os.curdir: |
Tim Golden | 6d09f09 | 2013-10-25 18:38:16 +0100 | [diff] [blame] | 202 | dir = _os.path.abspath(dir) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 203 | # Try only a few names per directory. |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 204 | for seq in range(100): |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 205 | name = next(namer) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 206 | filename = _os.path.join(dir, name) |
| 207 | try: |
Amaury Forgeot d'Arc | 7d0bddd | 2009-11-30 00:08:56 +0000 | [diff] [blame] | 208 | fd = _os.open(filename, _bin_openflags, 0o600) |
Serhiy Storchaka | f6b361e | 2013-02-13 00:35:30 +0200 | [diff] [blame] | 209 | try: |
| 210 | try: |
Serhiy Storchaka | 76a2ed1 | 2013-02-13 00:59:26 +0200 | [diff] [blame] | 211 | with _io.open(fd, 'wb', closefd=False) as fp: |
| 212 | fp.write(b'blat') |
Serhiy Storchaka | f6b361e | 2013-02-13 00:35:30 +0200 | [diff] [blame] | 213 | finally: |
| 214 | _os.close(fd) |
| 215 | finally: |
| 216 | _os.unlink(filename) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 217 | return dir |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 218 | except FileExistsError: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 219 | pass |
Serhiy Storchaka | 5d6b7b1 | 2015-05-20 00:11:48 +0300 | [diff] [blame] | 220 | except PermissionError: |
| 221 | # This exception is thrown when a directory with the chosen name |
| 222 | # already exists on windows. |
| 223 | if (_os.name == 'nt' and _os.path.isdir(dir) and |
| 224 | _os.access(dir, _os.W_OK)): |
| 225 | continue |
| 226 | break # no point trying more names in this directory |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 227 | except OSError: |
| 228 | break # no point trying more names in this directory |
Serhiy Storchaka | 7451a72 | 2013-02-09 22:25:49 +0200 | [diff] [blame] | 229 | raise FileNotFoundError(_errno.ENOENT, |
| 230 | "No usable temporary directory found in %s" % |
| 231 | dirlist) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 232 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 233 | _name_sequence = None |
| 234 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 235 | def _get_candidate_names(): |
| 236 | """Common setup sequence for all user-callable interfaces.""" |
| 237 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 238 | global _name_sequence |
| 239 | if _name_sequence is None: |
| 240 | _once_lock.acquire() |
| 241 | try: |
| 242 | if _name_sequence is None: |
| 243 | _name_sequence = _RandomNameSequence() |
| 244 | finally: |
| 245 | _once_lock.release() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 246 | return _name_sequence |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 247 | |
| 248 | |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 249 | def _mkstemp_inner(dir, pre, suf, flags, output_type): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 250 | """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.""" |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 251 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 252 | names = _get_candidate_names() |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 253 | if output_type is bytes: |
| 254 | names = map(_os.fsencode, names) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 255 | |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 256 | for seq in range(TMP_MAX): |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 257 | name = next(names) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 258 | file = _os.path.join(dir, pre + name + suf) |
| 259 | try: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 260 | fd = _os.open(file, flags, 0o600) |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 261 | except FileExistsError: |
| 262 | continue # try again |
Eli Bendersky | f315df3 | 2013-09-06 06:11:19 -0700 | [diff] [blame] | 263 | except PermissionError: |
| 264 | # This exception is thrown when a directory with the chosen name |
| 265 | # already exists on windows. |
Serhiy Storchaka | 5d6b7b1 | 2015-05-20 00:11:48 +0300 | [diff] [blame] | 266 | if (_os.name == 'nt' and _os.path.isdir(dir) and |
| 267 | _os.access(dir, _os.W_OK)): |
Eli Bendersky | f315df3 | 2013-09-06 06:11:19 -0700 | [diff] [blame] | 268 | continue |
| 269 | else: |
| 270 | raise |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 271 | return (fd, _os.path.abspath(file)) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 272 | |
Serhiy Storchaka | 7451a72 | 2013-02-09 22:25:49 +0200 | [diff] [blame] | 273 | raise FileExistsError(_errno.EEXIST, |
| 274 | "No usable temporary file name found") |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 275 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 276 | |
| 277 | # User visible interfaces. |
Guido van Rossum | b0e5718 | 1998-10-14 20:27:05 +0000 | [diff] [blame] | 278 | |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 279 | def gettempprefix(): |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 280 | """The default prefix for temporary directories.""" |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 281 | return template |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 282 | |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 283 | def gettempprefixb(): |
| 284 | """The default prefix for temporary directories as bytes.""" |
| 285 | return _os.fsencode(gettempprefix()) |
| 286 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 287 | tempdir = None |
| 288 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 289 | def gettempdir(): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 290 | """Accessor for tempfile.tempdir.""" |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 291 | global tempdir |
| 292 | if tempdir is None: |
| 293 | _once_lock.acquire() |
| 294 | try: |
| 295 | if tempdir is None: |
| 296 | tempdir = _get_default_tempdir() |
| 297 | finally: |
| 298 | _once_lock.release() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 299 | return tempdir |
| 300 | |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 301 | def gettempdirb(): |
| 302 | """A bytes version of tempfile.gettempdir().""" |
| 303 | return _os.fsencode(gettempdir()) |
| 304 | |
| 305 | def mkstemp(suffix=None, prefix=None, dir=None, text=False): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 306 | """User-callable function to create and return a unique temporary |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 307 | file. The return value is a pair (fd, name) where fd is the |
| 308 | file descriptor returned by os.open, and name is the filename. |
| 309 | |
Martin Panter | 9b566c3 | 2015-11-07 00:32:50 +0000 | [diff] [blame] | 310 | If 'suffix' is not None, the file name will end with that suffix, |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 311 | otherwise there will be no suffix. |
| 312 | |
Martin Panter | 9b566c3 | 2015-11-07 00:32:50 +0000 | [diff] [blame] | 313 | If 'prefix' is not None, the file name will begin with that prefix, |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 314 | otherwise a default prefix is used. |
| 315 | |
Martin Panter | 9b566c3 | 2015-11-07 00:32:50 +0000 | [diff] [blame] | 316 | If 'dir' is not None, the file will be created in that directory, |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 317 | otherwise a default directory is used. |
| 318 | |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 319 | If 'text' is specified and true, the file is opened in text |
| 320 | mode. Else (the default) the file is opened in binary mode. On |
| 321 | some operating systems, this makes no difference. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 322 | |
Martin Panter | 9b566c3 | 2015-11-07 00:32:50 +0000 | [diff] [blame] | 323 | If any of 'suffix', 'prefix' and 'dir' are not None, they must be the |
| 324 | same type. If they are bytes, the returned name will be bytes; str |
| 325 | otherwise. |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 326 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 327 | The file is readable and writable only by the creating user ID. |
| 328 | If the operating system uses permission bits to indicate whether a |
| 329 | file is executable, the file is executable by no one. The file |
| 330 | descriptor is not inherited by children of this process. |
| 331 | |
| 332 | Caller is responsible for deleting the file when done with it. |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 333 | """ |
| 334 | |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 335 | prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir) |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 336 | |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 337 | if text: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 338 | flags = _text_openflags |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 339 | else: |
| 340 | flags = _bin_openflags |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 341 | |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 342 | return _mkstemp_inner(dir, prefix, suffix, flags, output_type) |
Guido van Rossum | cff3454 | 1992-01-14 18:31:56 +0000 | [diff] [blame] | 343 | |
Guido van Rossum | eee9498 | 1991-11-12 15:38:08 +0000 | [diff] [blame] | 344 | |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 345 | def mkdtemp(suffix=None, prefix=None, dir=None): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 346 | """User-callable function to create and return a unique temporary |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 347 | directory. The return value is the pathname of the directory. |
| 348 | |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 349 | Arguments are as for mkstemp, except that the 'text' argument is |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 350 | not accepted. |
| 351 | |
| 352 | The directory is readable, writable, and searchable only by the |
| 353 | creating user. |
| 354 | |
| 355 | Caller is responsible for deleting the directory when done with it. |
| 356 | """ |
| 357 | |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 358 | prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir) |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 359 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 360 | names = _get_candidate_names() |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 361 | if output_type is bytes: |
| 362 | names = map(_os.fsencode, names) |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 363 | |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 364 | for seq in range(TMP_MAX): |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 365 | name = next(names) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 366 | file = _os.path.join(dir, prefix + name + suffix) |
| 367 | try: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 368 | _os.mkdir(file, 0o700) |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 369 | except FileExistsError: |
| 370 | continue # try again |
Serhiy Storchaka | 5d6b7b1 | 2015-05-20 00:11:48 +0300 | [diff] [blame] | 371 | except PermissionError: |
| 372 | # This exception is thrown when a directory with the chosen name |
| 373 | # already exists on windows. |
| 374 | if (_os.name == 'nt' and _os.path.isdir(dir) and |
| 375 | _os.access(dir, _os.W_OK)): |
| 376 | continue |
| 377 | else: |
| 378 | raise |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 379 | return file |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 380 | |
Serhiy Storchaka | 7451a72 | 2013-02-09 22:25:49 +0200 | [diff] [blame] | 381 | raise FileExistsError(_errno.EEXIST, |
| 382 | "No usable temporary directory name found") |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 383 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 384 | def mktemp(suffix="", prefix=template, dir=None): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 385 | """User-callable function to return a unique temporary file name. The |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 386 | file is not created. |
| 387 | |
Martin Panter | 9b566c3 | 2015-11-07 00:32:50 +0000 | [diff] [blame] | 388 | Arguments are similar to mkstemp, except that the 'text' argument is |
| 389 | not accepted, and suffix=None, prefix=None and bytes file names are not |
| 390 | supported. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 391 | |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 392 | THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may |
| 393 | refer to a file that did not exist at some point, but by the time |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 394 | you get around to creating it, someone else may have beaten you to |
| 395 | the punch. |
| 396 | """ |
| 397 | |
Guido van Rossum | 44f602d | 2002-11-22 15:56:29 +0000 | [diff] [blame] | 398 | ## from warnings import warn as _warn |
| 399 | ## _warn("mktemp is a potential security risk to your program", |
| 400 | ## RuntimeWarning, stacklevel=2) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 401 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 402 | if dir is None: |
| 403 | dir = gettempdir() |
| 404 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 405 | names = _get_candidate_names() |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 406 | for seq in range(TMP_MAX): |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 407 | name = next(names) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 408 | file = _os.path.join(dir, prefix + name + suffix) |
Guido van Rossum | b25615939 | 2003-11-10 02:16:36 +0000 | [diff] [blame] | 409 | if not _exists(file): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 410 | return file |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 411 | |
Serhiy Storchaka | 7451a72 | 2013-02-09 22:25:49 +0200 | [diff] [blame] | 412 | raise FileExistsError(_errno.EEXIST, |
| 413 | "No usable temporary filename found") |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 414 | |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 415 | |
Antoine Pitrou | 17c9326 | 2013-12-21 22:14:56 +0100 | [diff] [blame] | 416 | class _TemporaryFileCloser: |
| 417 | """A separate object allowing proper closing of a temporary file's |
| 418 | underlying file object, without adding a __del__ method to the |
| 419 | temporary file.""" |
Tim Peters | a255a72 | 2001-12-18 22:32:40 +0000 | [diff] [blame] | 420 | |
Serhiy Storchaka | a28632b | 2014-01-27 11:21:54 +0200 | [diff] [blame] | 421 | file = None # Set here since __del__ checks it |
Serhiy Storchaka | 99e033b | 2014-01-27 11:18:27 +0200 | [diff] [blame] | 422 | close_called = False |
| 423 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 424 | def __init__(self, file, name, delete=True): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 425 | self.file = file |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 426 | self.name = name |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 427 | self.delete = delete |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 428 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 429 | # NT provides delete-on-close as a primitive, so we don't need |
| 430 | # the wrapper to do anything special. We still use it so that |
| 431 | # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile. |
| 432 | if _os.name != 'nt': |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 433 | # Cache the unlinker so we don't get spurious errors at |
| 434 | # shutdown when the module-level "os" is None'd out. Note |
| 435 | # that this must be referenced as self.unlink, because the |
| 436 | # name TemporaryFileWrapper may also get None'd out before |
| 437 | # __del__ is called. |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 438 | |
Serhiy Storchaka | 99e033b | 2014-01-27 11:18:27 +0200 | [diff] [blame] | 439 | def close(self, unlink=_os.unlink): |
| 440 | if not self.close_called and self.file is not None: |
Tim Peters | 6ef966e | 2002-11-21 15:48:33 +0000 | [diff] [blame] | 441 | self.close_called = True |
Serhiy Storchaka | 7e7a3db | 2015-04-10 13:24:41 +0300 | [diff] [blame] | 442 | try: |
| 443 | self.file.close() |
| 444 | finally: |
| 445 | if self.delete: |
| 446 | unlink(self.name) |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 447 | |
Antoine Pitrou | 17c9326 | 2013-12-21 22:14:56 +0100 | [diff] [blame] | 448 | # Need to ensure the file is deleted on __del__ |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 449 | def __del__(self): |
| 450 | self.close() |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 451 | |
Benjamin Peterson | 98d23f2 | 2009-06-30 22:27:25 +0000 | [diff] [blame] | 452 | else: |
Antoine Pitrou | 17c9326 | 2013-12-21 22:14:56 +0100 | [diff] [blame] | 453 | def close(self): |
| 454 | if not self.close_called: |
| 455 | self.close_called = True |
| 456 | self.file.close() |
| 457 | |
| 458 | |
| 459 | class _TemporaryFileWrapper: |
| 460 | """Temporary file wrapper |
| 461 | |
| 462 | This class provides a wrapper around files opened for |
| 463 | temporary use. In particular, it seeks to automatically |
| 464 | remove the file when it is no longer needed. |
| 465 | """ |
| 466 | |
| 467 | def __init__(self, file, name, delete=True): |
| 468 | self.file = file |
| 469 | self.name = name |
| 470 | self.delete = delete |
| 471 | self._closer = _TemporaryFileCloser(file, name, delete) |
| 472 | |
| 473 | def __getattr__(self, name): |
| 474 | # Attribute lookups are delegated to the underlying file |
| 475 | # and cached for non-numeric results |
| 476 | # (i.e. methods are cached, closed and friends are not) |
| 477 | file = self.__dict__['file'] |
| 478 | a = getattr(file, name) |
| 479 | if hasattr(a, '__call__'): |
| 480 | func = a |
| 481 | @_functools.wraps(func) |
| 482 | def func_wrapper(*args, **kwargs): |
| 483 | return func(*args, **kwargs) |
| 484 | # Avoid closing the file as long as the wrapper is alive, |
| 485 | # see issue #18879. |
| 486 | func_wrapper._closer = self._closer |
| 487 | a = func_wrapper |
| 488 | if not isinstance(a, int): |
| 489 | setattr(self, name, a) |
| 490 | return a |
| 491 | |
| 492 | # The underlying __enter__ method returns the wrong object |
| 493 | # (self.file) so override it to return the wrapper |
| 494 | def __enter__(self): |
| 495 | self.file.__enter__() |
| 496 | return self |
| 497 | |
| 498 | # Need to trap __exit__ as well to ensure the file gets |
| 499 | # deleted when used in a with statement |
| 500 | def __exit__(self, exc, value, tb): |
| 501 | result = self.file.__exit__(exc, value, tb) |
| 502 | self.close() |
| 503 | return result |
| 504 | |
| 505 | def close(self): |
| 506 | """ |
| 507 | Close the temporary file, possibly deleting it. |
| 508 | """ |
| 509 | self._closer.close() |
| 510 | |
| 511 | # iter() doesn't use __getattr__ to find the __iter__ method |
| 512 | def __iter__(self): |
Serhiy Storchaka | d83b7c2 | 2015-03-20 16:11:20 +0200 | [diff] [blame] | 513 | # Don't return iter(self.file), but yield from it to avoid closing |
R David Murray | 75ed90a | 2015-03-22 12:33:46 -0400 | [diff] [blame] | 514 | # file as long as it's being used as iterator (see issue #23700). We |
| 515 | # can't use 'yield from' here because iter(file) returns the file |
| 516 | # object itself, which has a close method, and thus the file would get |
| 517 | # closed when the generator is finalized, due to PEP380 semantics. |
Serhiy Storchaka | d83b7c2 | 2015-03-20 16:11:20 +0200 | [diff] [blame] | 518 | for line in self.file: |
| 519 | yield line |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 520 | |
| 521 | |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 522 | def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 523 | newline=None, suffix=None, prefix=None, |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 524 | dir=None, delete=True): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 525 | """Create and return a temporary file. |
| 526 | Arguments: |
| 527 | 'prefix', 'suffix', 'dir' -- as for mkstemp. |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 528 | 'mode' -- the mode argument to io.open (default "w+b"). |
| 529 | 'buffering' -- the buffer size argument to io.open (default -1). |
| 530 | 'encoding' -- the encoding argument to io.open (default None) |
| 531 | 'newline' -- the newline argument to io.open (default None) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 532 | 'delete' -- whether the file is deleted on close (default True). |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 533 | The file is created as mkstemp() would do it. |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 534 | |
Raymond Hettinger | faa10eb | 2005-01-11 15:33:03 +0000 | [diff] [blame] | 535 | Returns an object with a file-like interface; the name of the file |
Martin Panter | 1f0e1f3 | 2016-02-22 10:10:00 +0000 | [diff] [blame] | 536 | is accessible as its 'name' attribute. The file will be automatically |
| 537 | deleted 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] | 538 | """ |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 539 | |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 540 | prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir) |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 541 | |
Amaury Forgeot d'Arc | 7d0bddd | 2009-11-30 00:08:56 +0000 | [diff] [blame] | 542 | flags = _bin_openflags |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 543 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 544 | # Setting O_TEMPORARY in the flags causes the OS to delete |
| 545 | # 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] | 546 | if _os.name == 'nt' and delete: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 547 | flags |= _os.O_TEMPORARY |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 548 | |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 549 | (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type) |
Victor Stinner | 1f99f9d | 2014-03-25 09:18:04 +0100 | [diff] [blame] | 550 | try: |
| 551 | file = _io.open(fd, mode, buffering=buffering, |
| 552 | newline=newline, encoding=encoding) |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 553 | |
Victor Stinner | 1f99f9d | 2014-03-25 09:18:04 +0100 | [diff] [blame] | 554 | return _TemporaryFileWrapper(file, name, delete) |
Martin Panter | 7869a22 | 2016-02-28 05:22:20 +0000 | [diff] [blame] | 555 | except BaseException: |
| 556 | _os.unlink(name) |
Victor Stinner | 1f99f9d | 2014-03-25 09:18:04 +0100 | [diff] [blame] | 557 | _os.close(fd) |
| 558 | raise |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 559 | |
Jason Tishler | 80c02af | 2002-08-14 15:10:09 +0000 | [diff] [blame] | 560 | if _os.name != 'posix' or _os.sys.platform == 'cygwin': |
| 561 | # On non-POSIX and Cygwin systems, assume that we cannot unlink a file |
| 562 | # while it is open. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 563 | TemporaryFile = NamedTemporaryFile |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 564 | |
| 565 | else: |
Victor Stinner | d967fc9 | 2014-06-05 14:27:45 +0200 | [diff] [blame] | 566 | # Is the O_TMPFILE flag available and does it work? |
| 567 | # The flag is set to False if os.open(dir, os.O_TMPFILE) raises an |
| 568 | # IsADirectoryError exception |
| 569 | _O_TMPFILE_WORKS = hasattr(_os, 'O_TMPFILE') |
| 570 | |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 571 | def TemporaryFile(mode='w+b', buffering=-1, encoding=None, |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 572 | newline=None, suffix=None, prefix=None, |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 573 | dir=None): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 574 | """Create and return a temporary file. |
| 575 | Arguments: |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 576 | 'prefix', 'suffix', 'dir' -- as for mkstemp. |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 577 | 'mode' -- the mode argument to io.open (default "w+b"). |
| 578 | 'buffering' -- the buffer size argument to io.open (default -1). |
| 579 | 'encoding' -- the encoding argument to io.open (default None) |
| 580 | 'newline' -- the newline argument to io.open (default None) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 581 | The file is created as mkstemp() would do it. |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 582 | |
Raymond Hettinger | faa10eb | 2005-01-11 15:33:03 +0000 | [diff] [blame] | 583 | Returns an object with a file-like interface. The file has no |
| 584 | name, and will cease to exist when it is closed. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 585 | """ |
Victor Stinner | d967fc9 | 2014-06-05 14:27:45 +0200 | [diff] [blame] | 586 | global _O_TMPFILE_WORKS |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 587 | |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 588 | prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir) |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 589 | |
Amaury Forgeot d'Arc | 7d0bddd | 2009-11-30 00:08:56 +0000 | [diff] [blame] | 590 | flags = _bin_openflags |
Victor Stinner | d967fc9 | 2014-06-05 14:27:45 +0200 | [diff] [blame] | 591 | if _O_TMPFILE_WORKS: |
| 592 | try: |
| 593 | flags2 = (flags | _os.O_TMPFILE) & ~_os.O_CREAT |
| 594 | fd = _os.open(dir, flags2, 0o600) |
| 595 | except IsADirectoryError: |
Victor Stinner | 9aba8c8 | 2015-10-21 00:15:08 +0200 | [diff] [blame] | 596 | # Linux kernel older than 3.11 ignores the O_TMPFILE flag: |
| 597 | # O_TMPFILE is read as O_DIRECTORY. Trying to open a directory |
| 598 | # with O_RDWR|O_DIRECTORY fails with IsADirectoryError, a |
| 599 | # directory cannot be open to write. Set flag to False to not |
| 600 | # try again. |
Victor Stinner | d967fc9 | 2014-06-05 14:27:45 +0200 | [diff] [blame] | 601 | _O_TMPFILE_WORKS = False |
| 602 | except OSError: |
| 603 | # The filesystem of the directory does not support O_TMPFILE. |
| 604 | # For example, OSError(95, 'Operation not supported'). |
Victor Stinner | 9aba8c8 | 2015-10-21 00:15:08 +0200 | [diff] [blame] | 605 | # |
| 606 | # On Linux kernel older than 3.11, trying to open a regular |
| 607 | # file (or a symbolic link to a regular file) with O_TMPFILE |
| 608 | # fails with NotADirectoryError, because O_TMPFILE is read as |
| 609 | # O_DIRECTORY. |
Victor Stinner | d967fc9 | 2014-06-05 14:27:45 +0200 | [diff] [blame] | 610 | pass |
| 611 | else: |
| 612 | try: |
| 613 | return _io.open(fd, mode, buffering=buffering, |
| 614 | newline=newline, encoding=encoding) |
| 615 | except: |
| 616 | _os.close(fd) |
| 617 | raise |
| 618 | # Fallback to _mkstemp_inner(). |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 619 | |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 620 | (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 621 | try: |
| 622 | _os.unlink(name) |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 623 | return _io.open(fd, mode, buffering=buffering, |
| 624 | newline=newline, encoding=encoding) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 625 | except: |
| 626 | _os.close(fd) |
| 627 | raise |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 628 | |
| 629 | class SpooledTemporaryFile: |
Serhiy Storchaka | 4f169a7 | 2013-02-09 11:46:42 +0200 | [diff] [blame] | 630 | """Temporary file wrapper, specialized to switch from BytesIO |
| 631 | or StringIO to a real file when it exceeds a certain size or |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 632 | when a fileno is needed. |
| 633 | """ |
| 634 | _rolled = False |
| 635 | |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 636 | def __init__(self, max_size=0, mode='w+b', buffering=-1, |
| 637 | encoding=None, newline=None, |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 638 | suffix=None, prefix=None, dir=None): |
Guido van Rossum | 9a63470 | 2007-07-09 10:24:45 +0000 | [diff] [blame] | 639 | if 'b' in mode: |
| 640 | self._file = _io.BytesIO() |
| 641 | else: |
Guido van Rossum | 5d21255 | 2007-10-29 16:42:51 +0000 | [diff] [blame] | 642 | # Setting newline="\n" avoids newline translation; |
| 643 | # this is important because otherwise on Windows we'd |
Yury Selivanov | 0b86660 | 2014-09-26 17:08:21 -0400 | [diff] [blame] | 644 | # get double newline translation upon rollover(). |
Alexandre Vassalotti | 3ade6f9 | 2008-06-12 01:13:54 +0000 | [diff] [blame] | 645 | self._file = _io.StringIO(newline="\n") |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 646 | self._max_size = max_size |
| 647 | self._rolled = False |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 648 | self._TemporaryFileArgs = {'mode': mode, 'buffering': buffering, |
| 649 | 'suffix': suffix, 'prefix': prefix, |
| 650 | 'encoding': encoding, 'newline': newline, |
| 651 | 'dir': dir} |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 652 | |
| 653 | def _check(self, file): |
| 654 | if self._rolled: return |
| 655 | max_size = self._max_size |
| 656 | if max_size and file.tell() > max_size: |
| 657 | self.rollover() |
| 658 | |
| 659 | def rollover(self): |
| 660 | if self._rolled: return |
| 661 | file = self._file |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 662 | newfile = self._file = TemporaryFile(**self._TemporaryFileArgs) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 663 | del self._TemporaryFileArgs |
| 664 | |
| 665 | newfile.write(file.getvalue()) |
| 666 | newfile.seek(file.tell(), 0) |
| 667 | |
| 668 | self._rolled = True |
| 669 | |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 670 | # The method caching trick from NamedTemporaryFile |
| 671 | # won't work here, because _file may change from a |
Serhiy Storchaka | 50254c5 | 2013-08-29 11:35:43 +0300 | [diff] [blame] | 672 | # BytesIO/StringIO instance to a real file. So we list |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 673 | # all the methods directly. |
| 674 | |
| 675 | # Context management protocol |
| 676 | def __enter__(self): |
| 677 | if self._file.closed: |
| 678 | raise ValueError("Cannot enter context with closed file") |
| 679 | return self |
| 680 | |
| 681 | def __exit__(self, exc, value, tb): |
| 682 | self._file.close() |
| 683 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 684 | # file protocol |
| 685 | def __iter__(self): |
| 686 | return self._file.__iter__() |
| 687 | |
| 688 | def close(self): |
| 689 | self._file.close() |
| 690 | |
| 691 | @property |
| 692 | def closed(self): |
| 693 | return self._file.closed |
| 694 | |
| 695 | @property |
| 696 | def encoding(self): |
Serhiy Storchaka | bbbbe8e | 2013-02-09 12:21:14 +0200 | [diff] [blame] | 697 | try: |
| 698 | return self._file.encoding |
| 699 | except AttributeError: |
| 700 | if 'b' in self._TemporaryFileArgs['mode']: |
| 701 | raise |
| 702 | return self._TemporaryFileArgs['encoding'] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 703 | |
| 704 | def fileno(self): |
| 705 | self.rollover() |
| 706 | return self._file.fileno() |
| 707 | |
| 708 | def flush(self): |
| 709 | self._file.flush() |
| 710 | |
| 711 | def isatty(self): |
| 712 | return self._file.isatty() |
| 713 | |
| 714 | @property |
| 715 | def mode(self): |
Serhiy Storchaka | bbbbe8e | 2013-02-09 12:21:14 +0200 | [diff] [blame] | 716 | try: |
| 717 | return self._file.mode |
| 718 | except AttributeError: |
| 719 | return self._TemporaryFileArgs['mode'] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 720 | |
| 721 | @property |
| 722 | def name(self): |
Serhiy Storchaka | bbbbe8e | 2013-02-09 12:21:14 +0200 | [diff] [blame] | 723 | try: |
| 724 | return self._file.name |
| 725 | except AttributeError: |
| 726 | return None |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 727 | |
| 728 | @property |
| 729 | def newlines(self): |
Serhiy Storchaka | bbbbe8e | 2013-02-09 12:21:14 +0200 | [diff] [blame] | 730 | try: |
| 731 | return self._file.newlines |
| 732 | except AttributeError: |
| 733 | if 'b' in self._TemporaryFileArgs['mode']: |
| 734 | raise |
| 735 | return self._TemporaryFileArgs['newline'] |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 736 | |
| 737 | def read(self, *args): |
| 738 | return self._file.read(*args) |
| 739 | |
| 740 | def readline(self, *args): |
| 741 | return self._file.readline(*args) |
| 742 | |
| 743 | def readlines(self, *args): |
| 744 | return self._file.readlines(*args) |
| 745 | |
| 746 | def seek(self, *args): |
| 747 | self._file.seek(*args) |
| 748 | |
| 749 | @property |
| 750 | def softspace(self): |
| 751 | return self._file.softspace |
| 752 | |
| 753 | def tell(self): |
| 754 | return self._file.tell() |
| 755 | |
Antoine Pitrou | 0e86a58 | 2011-11-25 18:03:09 +0100 | [diff] [blame] | 756 | def truncate(self, size=None): |
| 757 | if size is None: |
| 758 | self._file.truncate() |
| 759 | else: |
| 760 | if size > self._max_size: |
| 761 | self.rollover() |
| 762 | self._file.truncate(size) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 763 | |
| 764 | def write(self, s): |
| 765 | file = self._file |
| 766 | rv = file.write(s) |
| 767 | self._check(file) |
| 768 | return rv |
| 769 | |
| 770 | def writelines(self, iterable): |
| 771 | file = self._file |
| 772 | rv = file.writelines(iterable) |
| 773 | self._check(file) |
| 774 | return rv |
| 775 | |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 776 | |
| 777 | class TemporaryDirectory(object): |
| 778 | """Create and return a temporary directory. This has the same |
| 779 | behavior as mkdtemp but can be used as a context manager. For |
| 780 | example: |
| 781 | |
| 782 | with TemporaryDirectory() as tmpdir: |
| 783 | ... |
| 784 | |
Ezio Melotti | 30b9d5d | 2013-08-17 15:50:46 +0300 | [diff] [blame] | 785 | Upon exiting the context, the directory and everything contained |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 786 | in it are removed. |
| 787 | """ |
| 788 | |
Gregory P. Smith | ad577b9 | 2015-05-22 16:18:14 -0700 | [diff] [blame] | 789 | def __init__(self, suffix=None, prefix=None, dir=None): |
Nick Coghlan | 6b22f3f | 2010-12-12 15:24:21 +0000 | [diff] [blame] | 790 | self.name = mkdtemp(suffix, prefix, dir) |
Serhiy Storchaka | a28632b | 2014-01-27 11:21:54 +0200 | [diff] [blame] | 791 | self._finalizer = _weakref.finalize( |
| 792 | self, self._cleanup, self.name, |
| 793 | warn_message="Implicitly cleaning up {!r}".format(self)) |
| 794 | |
| 795 | @classmethod |
Serhiy Storchaka | 5e193ac | 2014-09-24 13:26:25 +0300 | [diff] [blame] | 796 | def _cleanup(cls, name, warn_message): |
Serhiy Storchaka | a28632b | 2014-01-27 11:21:54 +0200 | [diff] [blame] | 797 | _shutil.rmtree(name) |
Serhiy Storchaka | 5e193ac | 2014-09-24 13:26:25 +0300 | [diff] [blame] | 798 | _warnings.warn(warn_message, ResourceWarning) |
Serhiy Storchaka | a28632b | 2014-01-27 11:21:54 +0200 | [diff] [blame] | 799 | |
Nick Coghlan | 6b22f3f | 2010-12-12 15:24:21 +0000 | [diff] [blame] | 800 | def __repr__(self): |
| 801 | return "<{} {!r}>".format(self.__class__.__name__, self.name) |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 802 | |
| 803 | def __enter__(self): |
| 804 | return self.name |
| 805 | |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 806 | def __exit__(self, exc, value, tb): |
| 807 | self.cleanup() |
| 808 | |
Serhiy Storchaka | a28632b | 2014-01-27 11:21:54 +0200 | [diff] [blame] | 809 | def cleanup(self): |
Serhiy Storchaka | 5e193ac | 2014-09-24 13:26:25 +0300 | [diff] [blame] | 810 | if self._finalizer.detach(): |
Serhiy Storchaka | a28632b | 2014-01-27 11:21:54 +0200 | [diff] [blame] | 811 | _shutil.rmtree(self.name) |