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