| 1 |
"""Temporary files. |
| 2 |
|
| 3 |
This module provides generic, low- and high-level interfaces for |
| 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. |
| 8 |
|
| 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 |
|
| 17 |
This module also provides some data items to the user: |
| 18 |
|
| 19 |
TMP_MAX - maximum number of names that will be tried before |
| 20 |
giving up. |
| 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 |
""" |
| 25 |
|
| 26 |
__all__ = [ |
| 27 |
"NamedTemporaryFile", "TemporaryFile", |
| 28 |
"SpooledTemporaryFile", "TemporaryDirectory", |
| 29 |
"mkstemp", "mkdtemp", |
| 30 |
"mktemp", |
| 31 |
"TMP_MAX", "gettempprefix", |
| 32 |
"tempdir", "gettempdir", |
| 33 |
"gettempprefixb", "gettempdirb", |
| 34 |
] |
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
import functools as _functools |
| 40 |
import warnings as _warnings |
| 41 |
import io as _io |
| 42 |
import os as _os |
| 43 |
import shutil as _shutil |
| 44 |
import stat as _stat |
| 45 |
import errno as _errno |
| 46 |
from random import Random as _Random |
| 47 |
import sys as _sys |
| 48 |
import types as _types |
| 49 |
import weakref as _weakref |
| 50 |
import _thread |
| 51 |
_allocate_lock = _thread.allocate_lock |
| 52 |
|
| 53 |
_text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL |
| 54 |
if hasattr(_os, 'O_NOFOLLOW'): |
| 55 |
_text_openflags |= _os.O_NOFOLLOW |
| 56 |
|
| 57 |
_bin_openflags = _text_openflags |
| 58 |
if hasattr(_os, 'O_BINARY'): |
| 59 |
_bin_openflags |= _os.O_BINARY |
| 60 |
|
| 61 |
if hasattr(_os, 'TMP_MAX'): |
| 62 |
TMP_MAX = _os.TMP_MAX |
| 63 |
else: |
| 64 |
TMP_MAX = 10000 |
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
template = "tmp" |
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
_once_lock = _allocate_lock() |
| 75 |
|
| 76 |
|
| 77 |
def _exists(fn): |
| 78 |
try: |
| 79 |
_os.lstat(fn) |
| 80 |
except OSError: |
| 81 |
return False |
| 82 |
else: |
| 83 |
return True |
| 84 |
|
| 85 |
|
| 86 |
def _infer_return_type(*args): |
| 87 |
"""Look at the type of all args and divine their implied return type.""" |
| 88 |
return_type = None |
| 89 |
for arg in args: |
| 90 |
if arg is None: |
| 91 |
continue |
| 92 |
|
| 93 |
if isinstance(arg, _os.PathLike): |
| 94 |
arg = _os.fspath(arg) |
| 95 |
|
| 96 |
if isinstance(arg, bytes): |
| 97 |
if return_type is str: |
| 98 |
raise TypeError("Can't mix bytes and non-bytes in " |
| 99 |
"path components.") |
| 100 |
return_type = bytes |
| 101 |
else: |
| 102 |
if return_type is bytes: |
| 103 |
raise TypeError("Can't mix bytes and non-bytes in " |
| 104 |
"path components.") |
| 105 |
return_type = str |
| 106 |
if return_type is None: |
| 107 |
if tempdir is None or isinstance(tempdir, str): |
| 108 |
return str |
| 109 |
else: |
| 110 |
|
| 111 |
return bytes |
| 112 |
return return_type |
| 113 |
|
| 114 |
|
| 115 |
def _sanitize_params(prefix, suffix, dir): |
| 116 |
"""Common parameter processing for most APIs in this module.""" |
| 117 |
output_type = _infer_return_type(prefix, suffix, dir) |
| 118 |
if suffix is None: |
| 119 |
suffix = output_type() |
| 120 |
if prefix is None: |
| 121 |
if output_type is str: |
| 122 |
prefix = template |
| 123 |
else: |
| 124 |
prefix = _os.fsencode(template) |
| 125 |
if dir is None: |
| 126 |
if output_type is str: |
| 127 |
dir = gettempdir() |
| 128 |
else: |
| 129 |
dir = gettempdirb() |
| 130 |
return prefix, suffix, dir, output_type |
| 131 |
|
| 132 |
|
| 133 |
class _RandomNameSequence: |
| 134 |
"""An instance of _RandomNameSequence generates an endless |
| 135 |
sequence of unpredictable strings which can safely be incorporated |
| 136 |
into file names. Each string is eight characters long. Multiple |
| 137 |
threads can safely use the same instance at the same time. |
| 138 |
|
| 139 |
_RandomNameSequence is an iterator.""" |
| 140 |
|
| 141 |
characters = "abcdefghijklmnopqrstuvwxyz0123456789_" |
| 142 |
|
| 143 |
@property |
| 144 |
def rng(self): |
| 145 |
cur_pid = _os.getpid() |
| 146 |
if cur_pid != getattr(self, '_rng_pid', None): |
| 147 |
self._rng = _Random() |
| 148 |
self._rng_pid = cur_pid |
| 149 |
return self._rng |
| 150 |
|
| 151 |
def __iter__(self): |
| 152 |
return self |
| 153 |
|
| 154 |
def __next__(self): |
| 155 |
return ''.join(self.rng.choices(self.characters, k=8)) |
| 156 |
|
| 157 |
def _candidate_tempdir_list(): |
| 158 |
"""Generate a list of candidate temporary directories which |
| 159 |
_get_default_tempdir will try.""" |
| 160 |
|
| 161 |
dirlist = [] |
| 162 |
|
| 163 |
|
| 164 |
for envname in 'TMPDIR', 'TEMP', 'TMP': |
| 165 |
dirname = _os.getenv(envname) |
| 166 |
if dirname: dirlist.append(dirname) |
| 167 |
|
| 168 |
|
| 169 |
if _os.name == 'nt': |
| 170 |
dirlist.extend([ _os.path.expanduser(r'~\AppData\Local\Temp'), |
| 171 |
_os.path.expandvars(r'%SYSTEMROOT%\Temp'), |
| 172 |
r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ]) |
| 173 |
else: |
| 174 |
dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ]) |
| 175 |
|
| 176 |
|
| 177 |
try: |
| 178 |
dirlist.append(_os.getcwd()) |
| 179 |
except (AttributeError, OSError): |
| 180 |
dirlist.append(_os.curdir) |
| 181 |
|
| 182 |
return dirlist |
| 183 |
|
| 184 |
def _get_default_tempdir(): |
| 185 |
"""Calculate the default directory to use for temporary files. |
| 186 |
This routine should be called exactly once. |
| 187 |
|
| 188 |
We determine whether or not a candidate temp dir is usable by |
| 189 |
trying to create and write to a file in that directory. If this |
| 190 |
is successful, the test file is deleted. To prevent denial of |
| 191 |
service, the name of the test file must be randomized.""" |
| 192 |
|
| 193 |
namer = _RandomNameSequence() |
| 194 |
dirlist = _candidate_tempdir_list() |
| 195 |
|
| 196 |
for dir in dirlist: |
| 197 |
if dir != _os.curdir: |
| 198 |
dir = _os.path.abspath(dir) |
| 199 |
|
| 200 |
for seq in range(100): |
| 201 |
name = next(namer) |
| 202 |
filename = _os.path.join(dir, name) |
| 203 |
try: |
| 204 |
fd = _os.open(filename, _bin_openflags, 0o600) |
| 205 |
try: |
| 206 |
try: |
| 207 |
_os.write(fd, b'blat') |
| 208 |
finally: |
| 209 |
_os.close(fd) |
| 210 |
finally: |
| 211 |
_os.unlink(filename) |
| 212 |
return dir |
| 213 |
except FileExistsError: |
| 214 |
pass |
| 215 |
except PermissionError: |
| 216 |
|
| 217 |
|
| 218 |
if (_os.name == 'nt' and _os.path.isdir(dir) and |
| 219 |
_os.access(dir, _os.W_OK)): |
| 220 |
continue |
| 221 |
break |
| 222 |
except OSError: |
| 223 |
break |
| 224 |
raise FileNotFoundError(_errno.ENOENT, |
| 225 |
"No usable temporary directory found in %s" % |
| 226 |
dirlist) |
| 227 |
|
| 228 |
_name_sequence = None |
| 229 |
|
| 230 |
def _get_candidate_names(): |
| 231 |
"""Common setup sequence for all user-callable interfaces.""" |
| 232 |
|
| 233 |
global _name_sequence |
| 234 |
if _name_sequence is None: |
| 235 |
_once_lock.acquire() |
| 236 |
try: |
| 237 |
if _name_sequence is None: |
| 238 |
_name_sequence = _RandomNameSequence() |
| 239 |
finally: |
| 240 |
_once_lock.release() |
| 241 |
return _name_sequence |
| 242 |
|
| 243 |
|
| 244 |
def _mkstemp_inner(dir, pre, suf, flags, output_type): |
| 245 |
"""Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.""" |
| 246 |
|
| 247 |
dir = _os.path.abspath(dir) |
| 248 |
names = _get_candidate_names() |
| 249 |
if output_type is bytes: |
| 250 |
names = map(_os.fsencode, names) |
| 251 |
|
| 252 |
for seq in range(TMP_MAX): |
| 253 |
name = next(names) |
| 254 |
file = _os.path.join(dir, pre + name + suf) |
| 255 |
_sys.audit("tempfile.mkstemp", file) |
| 256 |
try: |
| 257 |
fd = _os.open(file, flags, 0o600) |
| 258 |
except FileExistsError: |
| 259 |
continue |
| 260 |
except PermissionError: |
| 261 |
|
| 262 |
|
| 263 |
if (_os.name == 'nt' and _os.path.isdir(dir) and |
| 264 |
_os.access(dir, _os.W_OK)): |
| 265 |
continue |
| 266 |
else: |
| 267 |
raise |
| 268 |
return fd, file |
| 269 |
|
| 270 |
raise FileExistsError(_errno.EEXIST, |
| 271 |
"No usable temporary file name found") |
| 272 |
|
| 273 |
def _dont_follow_symlinks(func, path, *args): |
| 274 |
|
| 275 |
if func in _os.supports_follow_symlinks: |
| 276 |
func(path, *args, follow_symlinks=False) |
| 277 |
elif _os.name == 'nt' or not _os.path.islink(path): |
| 278 |
func(path, *args) |
| 279 |
|
| 280 |
def _resetperms(path): |
| 281 |
try: |
| 282 |
chflags = _os.chflags |
| 283 |
except AttributeError: |
| 284 |
pass |
| 285 |
else: |
| 286 |
_dont_follow_symlinks(chflags, path, 0) |
| 287 |
_dont_follow_symlinks(_os.chmod, path, 0o700) |
| 288 |
|
| 289 |
|
| 290 |
|
| 291 |
|
| 292 |
def gettempprefix(): |
| 293 |
"""The default prefix for temporary directories as string.""" |
| 294 |
return _os.fsdecode(template) |
| 295 |
|
| 296 |
def gettempprefixb(): |
| 297 |
"""The default prefix for temporary directories as bytes.""" |
| 298 |
return _os.fsencode(template) |
| 299 |
|
| 300 |
tempdir = None |
| 301 |
|
| 302 |
def _gettempdir(): |
| 303 |
"""Private accessor for tempfile.tempdir.""" |
| 304 |
global tempdir |
| 305 |
if tempdir is None: |
| 306 |
_once_lock.acquire() |
| 307 |
try: |
| 308 |
if tempdir is None: |
| 309 |
tempdir = _get_default_tempdir() |
| 310 |
finally: |
| 311 |
_once_lock.release() |
| 312 |
return tempdir |
| 313 |
|
| 314 |
def gettempdir(): |
| 315 |
"""Returns tempfile.tempdir as str.""" |
| 316 |
return _os.fsdecode(_gettempdir()) |
| 317 |
|
| 318 |
def gettempdirb(): |
| 319 |
"""Returns tempfile.tempdir as bytes.""" |
| 320 |
return _os.fsencode(_gettempdir()) |
| 321 |
|
| 322 |
def mkstemp(suffix=None, prefix=None, dir=None, text=False): |
| 323 |
"""User-callable function to create and return a unique temporary |
| 324 |
file. The return value is a pair (fd, name) where fd is the |
| 325 |
file descriptor returned by os.open, and name is the filename. |
| 326 |
|
| 327 |
If 'suffix' is not None, the file name will end with that suffix, |
| 328 |
otherwise there will be no suffix. |
| 329 |
|
| 330 |
If 'prefix' is not None, the file name will begin with that prefix, |
| 331 |
otherwise a default prefix is used. |
| 332 |
|
| 333 |
If 'dir' is not None, the file will be created in that directory, |
| 334 |
otherwise a default directory is used. |
| 335 |
|
| 336 |
If 'text' is specified and true, the file is opened in text |
| 337 |
mode. Else (the default) the file is opened in binary mode. |
| 338 |
|
| 339 |
If any of 'suffix', 'prefix' and 'dir' are not None, they must be the |
| 340 |
same type. If they are bytes, the returned name will be bytes; str |
| 341 |
otherwise. |
| 342 |
|
| 343 |
The file is readable and writable only by the creating user ID. |
| 344 |
If the operating system uses permission bits to indicate whether a |
| 345 |
file is executable, the file is executable by no one. The file |
| 346 |
descriptor is not inherited by children of this process. |
| 347 |
|
| 348 |
Caller is responsible for deleting the file when done with it. |
| 349 |
""" |
| 350 |
|
| 351 |
prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir) |
| 352 |
|
| 353 |
if text: |
| 354 |
flags = _text_openflags |
| 355 |
else: |
| 356 |
flags = _bin_openflags |
| 357 |
|
| 358 |
return _mkstemp_inner(dir, prefix, suffix, flags, output_type) |
| 359 |
|
| 360 |
|
| 361 |
def mkdtemp(suffix=None, prefix=None, dir=None): |
| 362 |
"""User-callable function to create and return a unique temporary |
| 363 |
directory. The return value is the pathname of the directory. |
| 364 |
|
| 365 |
Arguments are as for mkstemp, except that the 'text' argument is |
| 366 |
not accepted. |
| 367 |
|
| 368 |
The directory is readable, writable, and searchable only by the |
| 369 |
creating user. |
| 370 |
|
| 371 |
Caller is responsible for deleting the directory when done with it. |
| 372 |
""" |
| 373 |
|
| 374 |
prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir) |
| 375 |
|
| 376 |
names = _get_candidate_names() |
| 377 |
if output_type is bytes: |
| 378 |
names = map(_os.fsencode, names) |
| 379 |
|
| 380 |
for seq in range(TMP_MAX): |
| 381 |
name = next(names) |
| 382 |
file = _os.path.join(dir, prefix + name + suffix) |
| 383 |
_sys.audit("tempfile.mkdtemp", file) |
| 384 |
try: |
| 385 |
_os.mkdir(file, 0o700) |
| 386 |
except FileExistsError: |
| 387 |
continue |
| 388 |
except PermissionError: |
| 389 |
|
| 390 |
|
| 391 |
if (_os.name == 'nt' and _os.path.isdir(dir) and |
| 392 |
_os.access(dir, _os.W_OK)): |
| 393 |
continue |
| 394 |
else: |
| 395 |
raise |
| 396 |
return file |
| 397 |
|
| 398 |
raise FileExistsError(_errno.EEXIST, |
| 399 |
"No usable temporary directory name found") |
| 400 |
|
| 401 |
def mktemp(suffix="", prefix=template, dir=None): |
| 402 |
"""User-callable function to return a unique temporary file name. The |
| 403 |
file is not created. |
| 404 |
|
| 405 |
Arguments are similar to mkstemp, except that the 'text' argument is |
| 406 |
not accepted, and suffix=None, prefix=None and bytes file names are not |
| 407 |
supported. |
| 408 |
|
| 409 |
THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may |
| 410 |
refer to a file that did not exist at some point, but by the time |
| 411 |
you get around to creating it, someone else may have beaten you to |
| 412 |
the punch. |
| 413 |
""" |
| 414 |
|
| 415 |
|
| 416 |
|
| 417 |
|
| 418 |
|
| 419 |
if dir is None: |
| 420 |
dir = gettempdir() |
| 421 |
|
| 422 |
names = _get_candidate_names() |
| 423 |
for seq in range(TMP_MAX): |
| 424 |
name = next(names) |
| 425 |
file = _os.path.join(dir, prefix + name + suffix) |
| 426 |
if not _exists(file): |
| 427 |
return file |
| 428 |
|
| 429 |
raise FileExistsError(_errno.EEXIST, |
| 430 |
"No usable temporary filename found") |
| 431 |
|
| 432 |
|
| 433 |
class _TemporaryFileCloser: |
| 434 |
"""A separate object allowing proper closing of a temporary file's |
| 435 |
underlying file object, without adding a __del__ method to the |
| 436 |
temporary file.""" |
| 437 |
|
| 438 |
file = None |
| 439 |
close_called = False |
| 440 |
|
| 441 |
def __init__(self, file, name, delete=True): |
| 442 |
self.file = file |
| 443 |
self.name = name |
| 444 |
self.delete = delete |
| 445 |
|
| 446 |
|
| 447 |
|
| 448 |
|
| 449 |
if _os.name != 'nt': |
| 450 |
|
| 451 |
|
| 452 |
|
| 453 |
|
| 454 |
|
| 455 |
|
| 456 |
def close(self, unlink=_os.unlink): |
| 457 |
if not self.close_called and self.file is not None: |
| 458 |
self.close_called = True |
| 459 |
try: |
| 460 |
self.file.close() |
| 461 |
finally: |
| 462 |
if self.delete: |
| 463 |
unlink(self.name) |
| 464 |
|
| 465 |
|
| 466 |
def __del__(self): |
| 467 |
self.close() |
| 468 |
|
| 469 |
else: |
| 470 |
def close(self): |
| 471 |
if not self.close_called: |
| 472 |
self.close_called = True |
| 473 |
self.file.close() |
| 474 |
|
| 475 |
|
| 476 |
class _TemporaryFileWrapper: |
| 477 |
"""Temporary file wrapper |
| 478 |
|
| 479 |
This class provides a wrapper around files opened for |
| 480 |
temporary use. In particular, it seeks to automatically |
| 481 |
remove the file when it is no longer needed. |
| 482 |
""" |
| 483 |
|
| 484 |
def __init__(self, file, name, delete=True): |
| 485 |
self.file = file |
| 486 |
self.name = name |
| 487 |
self.delete = delete |
| 488 |
self._closer = _TemporaryFileCloser(file, name, delete) |
| 489 |
|
| 490 |
def __getattr__(self, name): |
| 491 |
|
| 492 |
|
| 493 |
|
| 494 |
file = self.__dict__['file'] |
| 495 |
a = getattr(file, name) |
| 496 |
if hasattr(a, '__call__'): |
| 497 |
func = a |
| 498 |
@_functools.wraps(func) |
| 499 |
def func_wrapper(*args, **kwargs): |
| 500 |
return func(*args, **kwargs) |
| 501 |
|
| 502 |
|
| 503 |
func_wrapper._closer = self._closer |
| 504 |
a = func_wrapper |
| 505 |
if not isinstance(a, int): |
| 506 |
setattr(self, name, a) |
| 507 |
return a |
| 508 |
|
| 509 |
|
| 510 |
|
| 511 |
def __enter__(self): |
| 512 |
self.file.__enter__() |
| 513 |
return self |
| 514 |
|
| 515 |
|
| 516 |
|
| 517 |
def __exit__(self, exc, value, tb): |
| 518 |
result = self.file.__exit__(exc, value, tb) |
| 519 |
self.close() |
| 520 |
return result |
| 521 |
|
| 522 |
def close(self): |
| 523 |
""" |
| 524 |
Close the temporary file, possibly deleting it. |
| 525 |
""" |
| 526 |
self._closer.close() |
| 527 |
|
| 528 |
|
| 529 |
def __iter__(self): |
| 530 |
|
| 531 |
|
| 532 |
|
| 533 |
|
| 534 |
|
| 535 |
for line in self.file: |
| 536 |
yield line |
| 537 |
|
| 538 |
|
| 539 |
def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, |
| 540 |
newline=None, suffix=None, prefix=None, |
| 541 |
dir=None, delete=True, *, errors=None): |
| 542 |
"""Create and return a temporary file. |
| 543 |
Arguments: |
| 544 |
'prefix', 'suffix', 'dir' -- as for mkstemp. |
| 545 |
'mode' -- the mode argument to io.open (default "w+b"). |
| 546 |
'buffering' -- the buffer size argument to io.open (default -1). |
| 547 |
'encoding' -- the encoding argument to io.open (default None) |
| 548 |
'newline' -- the newline argument to io.open (default None) |
| 549 |
'delete' -- whether the file is deleted on close (default True). |
| 550 |
'errors' -- the errors argument to io.open (default None) |
| 551 |
The file is created as mkstemp() would do it. |
| 552 |
|
| 553 |
Returns an object with a file-like interface; the name of the file |
| 554 |
is accessible as its 'name' attribute. The file will be automatically |
| 555 |
deleted when it is closed unless the 'delete' argument is set to False. |
| 556 |
|
| 557 |
On POSIX, NamedTemporaryFiles cannot be automatically deleted if |
| 558 |
the creating process is terminated abruptly with a SIGKILL signal. |
| 559 |
Windows can delete the file even in this case. |
| 560 |
""" |
| 561 |
|
| 562 |
prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir) |
| 563 |
|
| 564 |
flags = _bin_openflags |
| 565 |
|
| 566 |
|
| 567 |
|
| 568 |
if _os.name == 'nt' and delete: |
| 569 |
flags |= _os.O_TEMPORARY |
| 570 |
|
| 571 |
if "b" not in mode: |
| 572 |
encoding = _io.text_encoding(encoding) |
| 573 |
|
| 574 |
name = None |
| 575 |
def opener(*args): |
| 576 |
nonlocal name |
| 577 |
fd, name = _mkstemp_inner(dir, prefix, suffix, flags, output_type) |
| 578 |
return fd |
| 579 |
try: |
| 580 |
file = _io.open(dir, mode, buffering=buffering, |
| 581 |
newline=newline, encoding=encoding, errors=errors, |
| 582 |
opener=opener) |
| 583 |
try: |
| 584 |
raw = getattr(file, 'buffer', file) |
| 585 |
raw = getattr(raw, 'raw', raw) |
| 586 |
raw.name = name |
| 587 |
return _TemporaryFileWrapper(file, name, delete) |
| 588 |
except: |
| 589 |
file.close() |
| 590 |
raise |
| 591 |
except: |
| 592 |
if name is not None and not (_os.name == 'nt' and delete): |
| 593 |
_os.unlink(name) |
| 594 |
raise |
| 595 |
|
| 596 |
if _os.name != 'posix' or _sys.platform == 'cygwin': |
| 597 |
|
| 598 |
|
| 599 |
TemporaryFile = NamedTemporaryFile |
| 600 |
|
| 601 |
else: |
| 602 |
|
| 603 |
|
| 604 |
|
| 605 |
_O_TMPFILE_WORKS = hasattr(_os, 'O_TMPFILE') |
| 606 |
|
| 607 |
def TemporaryFile(mode='w+b', buffering=-1, encoding=None, |
| 608 |
newline=None, suffix=None, prefix=None, |
| 609 |
dir=None, *, errors=None): |
| 610 |
"""Create and return a temporary file. |
| 611 |
Arguments: |
| 612 |
'prefix', 'suffix', 'dir' -- as for mkstemp. |
| 613 |
'mode' -- the mode argument to io.open (default "w+b"). |
| 614 |
'buffering' -- the buffer size argument to io.open (default -1). |
| 615 |
'encoding' -- the encoding argument to io.open (default None) |
| 616 |
'newline' -- the newline argument to io.open (default None) |
| 617 |
'errors' -- the errors argument to io.open (default None) |
| 618 |
The file is created as mkstemp() would do it. |
| 619 |
|
| 620 |
Returns an object with a file-like interface. The file has no |
| 621 |
name, and will cease to exist when it is closed. |
| 622 |
""" |
| 623 |
global _O_TMPFILE_WORKS |
| 624 |
|
| 625 |
if "b" not in mode: |
| 626 |
encoding = _io.text_encoding(encoding) |
| 627 |
|
| 628 |
prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir) |
| 629 |
|
| 630 |
flags = _bin_openflags |
| 631 |
if _O_TMPFILE_WORKS: |
| 632 |
fd = None |
| 633 |
def opener(*args): |
| 634 |
nonlocal fd |
| 635 |
flags2 = (flags | _os.O_TMPFILE) & ~_os.O_CREAT |
| 636 |
fd = _os.open(dir, flags2, 0o600) |
| 637 |
return fd |
| 638 |
try: |
| 639 |
file = _io.open(dir, mode, buffering=buffering, |
| 640 |
newline=newline, encoding=encoding, |
| 641 |
errors=errors, opener=opener) |
| 642 |
raw = getattr(file, 'buffer', file) |
| 643 |
raw = getattr(raw, 'raw', raw) |
| 644 |
raw.name = fd |
| 645 |
return file |
| 646 |
except IsADirectoryError: |
| 647 |
|
| 648 |
|
| 649 |
|
| 650 |
|
| 651 |
|
| 652 |
_O_TMPFILE_WORKS = False |
| 653 |
except OSError: |
| 654 |
|
| 655 |
|
| 656 |
|
| 657 |
|
| 658 |
|
| 659 |
|
| 660 |
|
| 661 |
pass |
| 662 |
|
| 663 |
|
| 664 |
fd = None |
| 665 |
def opener(*args): |
| 666 |
nonlocal fd |
| 667 |
fd, name = _mkstemp_inner(dir, prefix, suffix, flags, output_type) |
| 668 |
try: |
| 669 |
_os.unlink(name) |
| 670 |
except BaseException as e: |
| 671 |
_os.close(fd) |
| 672 |
raise |
| 673 |
return fd |
| 674 |
file = _io.open(dir, mode, buffering=buffering, |
| 675 |
newline=newline, encoding=encoding, errors=errors, |
| 676 |
opener=opener) |
| 677 |
raw = getattr(file, 'buffer', file) |
| 678 |
raw = getattr(raw, 'raw', raw) |
| 679 |
raw.name = fd |
| 680 |
return file |
| 681 |
|
| 682 |
class SpooledTemporaryFile(_io.IOBase): |
| 683 |
"""Temporary file wrapper, specialized to switch from BytesIO |
| 684 |
or StringIO to a real file when it exceeds a certain size or |
| 685 |
when a fileno is needed. |
| 686 |
""" |
| 687 |
_rolled = False |
| 688 |
|
| 689 |
def __init__(self, max_size=0, mode='w+b', buffering=-1, |
| 690 |
encoding=None, newline=None, |
| 691 |
suffix=None, prefix=None, dir=None, *, errors=None): |
| 692 |
if 'b' in mode: |
| 693 |
self._file = _io.BytesIO() |
| 694 |
else: |
| 695 |
encoding = _io.text_encoding(encoding) |
| 696 |
self._file = _io.TextIOWrapper(_io.BytesIO(), |
| 697 |
encoding=encoding, errors=errors, |
| 698 |
newline=newline) |
| 699 |
self._max_size = max_size |
| 700 |
self._rolled = False |
| 701 |
self._TemporaryFileArgs = {'mode': mode, 'buffering': buffering, |
| 702 |
'suffix': suffix, 'prefix': prefix, |
| 703 |
'encoding': encoding, 'newline': newline, |
| 704 |
'dir': dir, 'errors': errors} |
| 705 |
|
| 706 |
__class_getitem__ = classmethod(_types.GenericAlias) |
| 707 |
|
| 708 |
def _check(self, file): |
| 709 |
if self._rolled: return |
| 710 |
max_size = self._max_size |
| 711 |
if max_size and file.tell() > max_size: |
| 712 |
self.rollover() |
| 713 |
|
| 714 |
def rollover(self): |
| 715 |
if self._rolled: return |
| 716 |
file = self._file |
| 717 |
newfile = self._file = TemporaryFile(**self._TemporaryFileArgs) |
| 718 |
del self._TemporaryFileArgs |
| 719 |
|
| 720 |
pos = file.tell() |
| 721 |
if hasattr(newfile, 'buffer'): |
| 722 |
newfile.buffer.write(file.detach().getvalue()) |
| 723 |
else: |
| 724 |
newfile.write(file.getvalue()) |
| 725 |
newfile.seek(pos, 0) |
| 726 |
|
| 727 |
self._rolled = True |
| 728 |
|
| 729 |
|
| 730 |
|
| 731 |
|
| 732 |
|
| 733 |
|
| 734 |
|
| 735 |
def __enter__(self): |
| 736 |
if self._file.closed: |
| 737 |
raise ValueError("Cannot enter context with closed file") |
| 738 |
return self |
| 739 |
|
| 740 |
def __exit__(self, exc, value, tb): |
| 741 |
self._file.close() |
| 742 |
|
| 743 |
|
| 744 |
def __iter__(self): |
| 745 |
return self._file.__iter__() |
| 746 |
|
| 747 |
def __del__(self): |
| 748 |
if not self.closed: |
| 749 |
_warnings.warn( |
| 750 |
"Unclosed file {!r}".format(self), |
| 751 |
ResourceWarning, |
| 752 |
stacklevel=2, |
| 753 |
source=self |
| 754 |
) |
| 755 |
self.close() |
| 756 |
|
| 757 |
def close(self): |
| 758 |
self._file.close() |
| 759 |
|
| 760 |
@property |
| 761 |
def closed(self): |
| 762 |
return self._file.closed |
| 763 |
|
| 764 |
@property |
| 765 |
def encoding(self): |
| 766 |
return self._file.encoding |
| 767 |
|
| 768 |
@property |
| 769 |
def errors(self): |
| 770 |
return self._file.errors |
| 771 |
|
| 772 |
def fileno(self): |
| 773 |
self.rollover() |
| 774 |
return self._file.fileno() |
| 775 |
|
| 776 |
def flush(self): |
| 777 |
self._file.flush() |
| 778 |
|
| 779 |
def isatty(self): |
| 780 |
return self._file.isatty() |
| 781 |
|
| 782 |
@property |
| 783 |
def mode(self): |
| 784 |
try: |
| 785 |
return self._file.mode |
| 786 |
except AttributeError: |
| 787 |
return self._TemporaryFileArgs['mode'] |
| 788 |
|
| 789 |
@property |
| 790 |
def name(self): |
| 791 |
try: |
| 792 |
return self._file.name |
| 793 |
except AttributeError: |
| 794 |
return None |
| 795 |
|
| 796 |
@property |
| 797 |
def newlines(self): |
| 798 |
return self._file.newlines |
| 799 |
|
| 800 |
def readable(self): |
| 801 |
return self._file.readable() |
| 802 |
|
| 803 |
def read(self, *args): |
| 804 |
return self._file.read(*args) |
| 805 |
|
| 806 |
def read1(self, *args): |
| 807 |
return self._file.read1(*args) |
| 808 |
|
| 809 |
def readinto(self, b): |
| 810 |
return self._file.readinto(b) |
| 811 |
|
| 812 |
def readinto1(self, b): |
| 813 |
return self._file.readinto1(b) |
| 814 |
|
| 815 |
def readline(self, *args): |
| 816 |
return self._file.readline(*args) |
| 817 |
|
| 818 |
def readlines(self, *args): |
| 819 |
return self._file.readlines(*args) |
| 820 |
|
| 821 |
def seekable(self): |
| 822 |
return self._file.seekable() |
| 823 |
|
| 824 |
def seek(self, *args): |
| 825 |
return self._file.seek(*args) |
| 826 |
|
| 827 |
def tell(self): |
| 828 |
return self._file.tell() |
| 829 |
|
| 830 |
def truncate(self, size=None): |
| 831 |
if size is None: |
| 832 |
return self._file.truncate() |
| 833 |
else: |
| 834 |
if size > self._max_size: |
| 835 |
self.rollover() |
| 836 |
return self._file.truncate(size) |
| 837 |
|
| 838 |
def writable(self): |
| 839 |
return self._file.writable() |
| 840 |
|
| 841 |
def write(self, s): |
| 842 |
file = self._file |
| 843 |
rv = file.write(s) |
| 844 |
self._check(file) |
| 845 |
return rv |
| 846 |
|
| 847 |
def writelines(self, iterable): |
| 848 |
file = self._file |
| 849 |
rv = file.writelines(iterable) |
| 850 |
self._check(file) |
| 851 |
return rv |
| 852 |
|
| 853 |
def detach(self): |
| 854 |
return self._file.detach() |
| 855 |
|
| 856 |
|
| 857 |
class TemporaryDirectory: |
| 858 |
"""Create and return a temporary directory. This has the same |
| 859 |
behavior as mkdtemp but can be used as a context manager. For |
| 860 |
example: |
| 861 |
|
| 862 |
with TemporaryDirectory() as tmpdir: |
| 863 |
... |
| 864 |
|
| 865 |
Upon exiting the context, the directory and everything contained |
| 866 |
in it are removed. |
| 867 |
""" |
| 868 |
|
| 869 |
def __init__(self, suffix=None, prefix=None, dir=None, |
| 870 |
ignore_cleanup_errors=False): |
| 871 |
self.name = mkdtemp(suffix, prefix, dir) |
| 872 |
self._ignore_cleanup_errors = ignore_cleanup_errors |
| 873 |
self._finalizer = _weakref.finalize( |
| 874 |
self, self._cleanup, self.name, |
| 875 |
warn_message="Implicitly cleaning up {!r}".format(self), |
| 876 |
ignore_errors=self._ignore_cleanup_errors) |
| 877 |
|
| 878 |
@classmethod |
| 879 |
def _rmtree(cls, name, ignore_errors=False, repeated=False): |
| 880 |
def onerror(func, path, exc_info): |
| 881 |
if issubclass(exc_info[0], PermissionError): |
| 882 |
if repeated and path == name: |
| 883 |
if ignore_errors: |
| 884 |
return |
| 885 |
raise |
| 886 |
|
| 887 |
try: |
| 888 |
if path != name: |
| 889 |
_resetperms(_os.path.dirname(path)) |
| 890 |
_resetperms(path) |
| 891 |
|
| 892 |
try: |
| 893 |
_os.unlink(path) |
| 894 |
except IsADirectoryError: |
| 895 |
cls._rmtree(path, ignore_errors=ignore_errors) |
| 896 |
except PermissionError: |
| 897 |
|
| 898 |
|
| 899 |
|
| 900 |
|
| 901 |
|
| 902 |
|
| 903 |
|
| 904 |
try: |
| 905 |
st = _os.lstat(path) |
| 906 |
except OSError: |
| 907 |
if ignore_errors: |
| 908 |
return |
| 909 |
raise |
| 910 |
if (_stat.S_ISLNK(st.st_mode) or |
| 911 |
not _stat.S_ISDIR(st.st_mode) or |
| 912 |
(hasattr(st, 'st_file_attributes') and |
| 913 |
st.st_file_attributes & _stat.FILE_ATTRIBUTE_REPARSE_POINT and |
| 914 |
st.st_reparse_tag == _stat.IO_REPARSE_TAG_MOUNT_POINT) |
| 915 |
): |
| 916 |
if ignore_errors: |
| 917 |
return |
| 918 |
raise |
| 919 |
cls._rmtree(path, ignore_errors=ignore_errors, |
| 920 |
repeated=(path == name)) |
| 921 |
except FileNotFoundError: |
| 922 |
pass |
| 923 |
elif issubclass(exc_info[0], FileNotFoundError): |
| 924 |
pass |
| 925 |
else: |
| 926 |
if not ignore_errors: |
| 927 |
raise |
| 928 |
|
| 929 |
_shutil.rmtree(name, onerror=onerror) |
| 930 |
|
| 931 |
@classmethod |
| 932 |
def _cleanup(cls, name, warn_message, ignore_errors=False): |
| 933 |
cls._rmtree(name, ignore_errors=ignore_errors) |
| 934 |
_warnings.warn(warn_message, ResourceWarning) |
| 935 |
|
| 936 |
def __repr__(self): |
| 937 |
return "<{} {!r}>".format(self.__class__.__name__, self.name) |
| 938 |
|
| 939 |
def __enter__(self): |
| 940 |
return self.name |
| 941 |
|
| 942 |
def __exit__(self, exc, value, tb): |
| 943 |
self.cleanup() |
| 944 |
|
| 945 |
def cleanup(self): |
| 946 |
if self._finalizer.detach() or _os.path.exists(self.name): |
| 947 |
self._rmtree(self.name, ignore_errors=self._ignore_cleanup_errors) |
| 948 |
|
| 949 |
__class_getitem__ = classmethod(_types.GenericAlias) |