tempfile.py 26 KB
Newer Older
1
"""Temporary files.
2

3
This module provides generic, low- and high-level interfaces for
4 5 6 7
creating temporary files and directories.  All of the interfaces
provided by this module can be used without fear of race conditions
except for 'mktemp'.  'mktemp' is subject to race conditions and
should not be used; it is provided for backward compatibility only.
Guido van Rossum's avatar
Guido van Rossum committed
8

9 10 11 12 13 14 15 16
The default path names are returned as str.  If you supply bytes as
input, all return values will be in bytes.  Ex:

    >>> tempfile.mkstemp()
    (4, '/tmp/tmptpu9nin8')
    >>> tempfile.mkdtemp(suffix=b'')
    b'/tmp/tmppbi8f0hy'

17
This module also provides some data items to the user:
Guido van Rossum's avatar
Guido van Rossum committed
18

19 20 21 22 23 24 25 26 27
  TMP_MAX  - maximum number of names that will be tried before
             giving up.
  tempdir  - If this is set to a string before the first use of
             any routine from this module, it will be considered as
             another candidate location to store temporary files.
"""

__all__ = [
    "NamedTemporaryFile", "TemporaryFile", # high level safe interfaces
28
    "SpooledTemporaryFile", "TemporaryDirectory",
29 30 31
    "mkstemp", "mkdtemp",                  # low level safe interfaces
    "mktemp",                              # deprecated unsafe interface
    "TMP_MAX", "gettempprefix",            # constants
32 33
    "tempdir", "gettempdir",
    "gettempprefixb", "gettempdirb",
34 35 36 37 38
   ]


# Imports.

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 errno as _errno
45
from random import Random as _Random
46
import weakref as _weakref
47 48

try:
49
    import _thread
50
except ImportError:
51
    import _dummy_thread as _thread
52
_allocate_lock = _thread.allocate_lock
53 54

_text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL
Tim Peters's avatar
Tim Peters committed
55 56
if hasattr(_os, 'O_NOFOLLOW'):
    _text_openflags |= _os.O_NOFOLLOW
57 58

_bin_openflags = _text_openflags
Tim Peters's avatar
Tim Peters committed
59 60
if hasattr(_os, 'O_BINARY'):
    _bin_openflags |= _os.O_BINARY
61 62 63 64 65 66

if hasattr(_os, 'TMP_MAX'):
    TMP_MAX = _os.TMP_MAX
else:
    TMP_MAX = 10000

67 68 69 70
# This variable _was_ unused for legacy reasons, see issue 10354.
# But as of 3.5 we actually use it at runtime so changing it would
# have a possibly desirable side effect...  But we do not want to support
# that as an API.  It is undocumented on purpose.  Do not depend on this.
71
template = "tmp"
72

73 74 75 76
# Internal routines.

_once_lock = _allocate_lock()

77 78 79 80 81
if hasattr(_os, "lstat"):
    _stat = _os.lstat
elif hasattr(_os, "stat"):
    _stat = _os.stat
else:
82
    # Fallback.  All we need is something that raises OSError if the
83 84
    # file doesn't exist.
    def _stat(fn):
85
        fd = _os.open(fn, _os.O_RDONLY)
86
        _os.close(fd)
87 88 89 90

def _exists(fn):
    try:
        _stat(fn)
91
    except OSError:
92 93 94 95
        return False
    else:
        return True

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135

def _infer_return_type(*args):
    """Look at the type of all args and divine their implied return type."""
    return_type = None
    for arg in args:
        if arg is None:
            continue
        if isinstance(arg, bytes):
            if return_type is str:
                raise TypeError("Can't mix bytes and non-bytes in "
                                "path components.")
            return_type = bytes
        else:
            if return_type is bytes:
                raise TypeError("Can't mix bytes and non-bytes in "
                                "path components.")
            return_type = str
    if return_type is None:
        return str  # tempfile APIs return a str by default.
    return return_type


def _sanitize_params(prefix, suffix, dir):
    """Common parameter processing for most APIs in this module."""
    output_type = _infer_return_type(prefix, suffix, dir)
    if suffix is None:
        suffix = output_type()
    if prefix is None:
        if output_type is str:
            prefix = template
        else:
            prefix = _os.fsencode(template)
    if dir is None:
        if output_type is str:
            dir = gettempdir()
        else:
            dir = gettempdirb()
    return prefix, suffix, dir, output_type


136 137 138 139 140 141 142 143
class _RandomNameSequence:
    """An instance of _RandomNameSequence generates an endless
    sequence of unpredictable strings which can safely be incorporated
    into file names.  Each string is six characters long.  Multiple
    threads can safely use the same instance at the same time.

    _RandomNameSequence is an iterator."""

Raymond Hettinger's avatar
Raymond Hettinger committed
144
    characters = "abcdefghijklmnopqrstuvwxyz0123456789_"
145

146 147 148 149 150 151 152
    @property
    def rng(self):
        cur_pid = _os.getpid()
        if cur_pid != getattr(self, '_rng_pid', None):
            self._rng = _Random()
            self._rng_pid = cur_pid
        return self._rng
153

154 155 156
    def __iter__(self):
        return self

157
    def __next__(self):
158
        c = self.characters
159
        choose = self.rng.choice
160
        letters = [choose(c) for dummy in range(8)]
Raymond Hettinger's avatar
Raymond Hettinger committed
161
        return ''.join(letters)
162 163 164 165 166 167 168 169

def _candidate_tempdir_list():
    """Generate a list of candidate temporary directories which
    _get_default_tempdir will try."""

    dirlist = []

    # First, try the environment.
170
    for envname in 'TMPDIR', 'TEMP', 'TMP':
171 172 173 174
        dirname = _os.getenv(envname)
        if dirname: dirlist.append(dirname)

    # Failing that, try OS-specific locations.
175
    if _os.name == 'nt':
176 177 178 179 180 181 182
        dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
    else:
        dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])

    # As a last resort, the current directory.
    try:
        dirlist.append(_os.getcwd())
183
    except (AttributeError, OSError):
184 185 186
        dirlist.append(_os.curdir)

    return dirlist
Tim Peters's avatar
Tim Peters committed
187

188 189
def _get_default_tempdir():
    """Calculate the default directory to use for temporary files.
190
    This routine should be called exactly once.
191 192 193 194 195 196 197 198 199 200 201

    We determine whether or not a candidate temp dir is usable by
    trying to create and write to a file in that directory.  If this
    is successful, the test file is deleted.  To prevent denial of
    service, the name of the test file must be randomized."""

    namer = _RandomNameSequence()
    dirlist = _candidate_tempdir_list()

    for dir in dirlist:
        if dir != _os.curdir:
202
            dir = _os.path.abspath(dir)
203
        # Try only a few names per directory.
204
        for seq in range(100):
205
            name = next(namer)
206 207
            filename = _os.path.join(dir, name)
            try:
208
                fd = _os.open(filename, _bin_openflags, 0o600)
209 210
                try:
                    try:
211 212
                        with _io.open(fd, 'wb', closefd=False) as fp:
                            fp.write(b'blat')
213 214 215 216
                    finally:
                        _os.close(fd)
                finally:
                    _os.unlink(filename)
217
                return dir
218
            except FileExistsError:
219
                pass
220 221 222 223 224 225 226
            except PermissionError:
                # This exception is thrown when a directory with the chosen name
                # already exists on windows.
                if (_os.name == 'nt' and _os.path.isdir(dir) and
                    _os.access(dir, _os.W_OK)):
                    continue
                break   # no point trying more names in this directory
227 228
            except OSError:
                break   # no point trying more names in this directory
229 230 231
    raise FileNotFoundError(_errno.ENOENT,
                            "No usable temporary directory found in %s" %
                            dirlist)
232

233 234
_name_sequence = None

235 236
def _get_candidate_names():
    """Common setup sequence for all user-callable interfaces."""
237

238 239 240 241 242 243 244 245
    global _name_sequence
    if _name_sequence is None:
        _once_lock.acquire()
        try:
            if _name_sequence is None:
                _name_sequence = _RandomNameSequence()
        finally:
            _once_lock.release()
246 247 248
    return _name_sequence


249
def _mkstemp_inner(dir, pre, suf, flags, output_type):
250 251 252
    """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""

    names = _get_candidate_names()
253 254
    if output_type is bytes:
        names = map(_os.fsencode, names)
255

256
    for seq in range(TMP_MAX):
257
        name = next(names)
258 259
        file = _os.path.join(dir, pre + name + suf)
        try:
260
            fd = _os.open(file, flags, 0o600)
261 262
        except FileExistsError:
            continue    # try again
263 264 265
        except PermissionError:
            # This exception is thrown when a directory with the chosen name
            # already exists on windows.
266 267
            if (_os.name == 'nt' and _os.path.isdir(dir) and
                _os.access(dir, _os.W_OK)):
268 269 270
                continue
            else:
                raise
271
        return (fd, _os.path.abspath(file))
272

273 274
    raise FileExistsError(_errno.EEXIST,
                          "No usable temporary file name found")
Tim Peters's avatar
Tim Peters committed
275

276 277

# User visible interfaces.
278

279
def gettempprefix():
280
    """The default prefix for temporary directories."""
281 282
    return template

283 284 285 286
def gettempprefixb():
    """The default prefix for temporary directories as bytes."""
    return _os.fsencode(gettempprefix())

287 288
tempdir = None

289
def gettempdir():
Christian Heimes's avatar
Christian Heimes committed
290
    """Accessor for tempfile.tempdir."""
291 292 293 294 295 296 297 298
    global tempdir
    if tempdir is None:
        _once_lock.acquire()
        try:
            if tempdir is None:
                tempdir = _get_default_tempdir()
        finally:
            _once_lock.release()
299 300
    return tempdir

301 302 303 304 305
def gettempdirb():
    """A bytes version of tempfile.gettempdir()."""
    return _os.fsencode(gettempdir())

def mkstemp(suffix=None, prefix=None, dir=None, text=False):
Christian Heimes's avatar
Christian Heimes committed
306
    """User-callable function to create and return a unique temporary
307 308 309
    file.  The return value is a pair (fd, name) where fd is the
    file descriptor returned by os.open, and name is the filename.

310
    If 'suffix' is not None, the file name will end with that suffix,
311 312
    otherwise there will be no suffix.

313
    If 'prefix' is not None, the file name will begin with that prefix,
314 315
    otherwise a default prefix is used.

316
    If 'dir' is not None, the file will be created in that directory,
317 318
    otherwise a default directory is used.

319 320 321
    If 'text' is specified and true, the file is opened in text
    mode.  Else (the default) the file is opened in binary mode.  On
    some operating systems, this makes no difference.
322

323 324 325
    If any of 'suffix', 'prefix' and 'dir' are not None, they must be the
    same type.  If they are bytes, the returned name will be bytes; str
    otherwise.
326

327 328 329 330
    The file is readable and writable only by the creating user ID.
    If the operating system uses permission bits to indicate whether a
    file is executable, the file is executable by no one. The file
    descriptor is not inherited by children of this process.
331

332
    Caller is responsible for deleting the file when done with it.
333 334
    """

335
    prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
336

337
    if text:
338
        flags = _text_openflags
339 340
    else:
        flags = _bin_openflags
341

342
    return _mkstemp_inner(dir, prefix, suffix, flags, output_type)
Guido van Rossum's avatar
Guido van Rossum committed
343

344

345
def mkdtemp(suffix=None, prefix=None, dir=None):
Christian Heimes's avatar
Christian Heimes committed
346
    """User-callable function to create and return a unique temporary
347 348
    directory.  The return value is the pathname of the directory.

349
    Arguments are as for mkstemp, except that the 'text' argument is
350 351 352 353 354 355 356 357
    not accepted.

    The directory is readable, writable, and searchable only by the
    creating user.

    Caller is responsible for deleting the directory when done with it.
    """

358
    prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
359

360
    names = _get_candidate_names()
361 362
    if output_type is bytes:
        names = map(_os.fsencode, names)
Tim Peters's avatar
Tim Peters committed
363

364
    for seq in range(TMP_MAX):
365
        name = next(names)
366 367
        file = _os.path.join(dir, prefix + name + suffix)
        try:
368
            _os.mkdir(file, 0o700)
369 370
        except FileExistsError:
            continue    # try again
371 372 373 374 375 376 377 378
        except PermissionError:
            # This exception is thrown when a directory with the chosen name
            # already exists on windows.
            if (_os.name == 'nt' and _os.path.isdir(dir) and
                _os.access(dir, _os.W_OK)):
                continue
            else:
                raise
379
        return file
380

381 382
    raise FileExistsError(_errno.EEXIST,
                          "No usable temporary directory name found")
383

384
def mktemp(suffix="", prefix=template, dir=None):
Christian Heimes's avatar
Christian Heimes committed
385
    """User-callable function to return a unique temporary file name.  The
386
    file is not created.
387

388 389 390
    Arguments are similar to mkstemp, except that the 'text' argument is
    not accepted, and suffix=None, prefix=None and bytes file names are not
    supported.
391

392 393
    THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED.  The file name may
    refer to a file that did not exist at some point, but by the time
394 395
    you get around to creating it, someone else may have beaten you to
    the punch.
396
    """
397

398 399 400
##    from warnings import warn as _warn
##    _warn("mktemp is a potential security risk to your program",
##          RuntimeWarning, stacklevel=2)
401

402 403 404
    if dir is None:
        dir = gettempdir()

405
    names = _get_candidate_names()
406
    for seq in range(TMP_MAX):
407
        name = next(names)
408
        file = _os.path.join(dir, prefix + name + suffix)
409
        if not _exists(file):
410 411
            return file

412 413
    raise FileExistsError(_errno.EEXIST,
                          "No usable temporary filename found")
414

Christian Heimes's avatar
Christian Heimes committed
415

416 417 418 419 420
class _TemporaryFileCloser:
    """A separate object allowing proper closing of a temporary file's
    underlying file object, without adding a __del__ method to the
    temporary file."""

421
    file = None  # Set here since __del__ checks it
422 423
    close_called = False

424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
    def __init__(self, file, name, delete=True):
        self.file = file
        self.name = name
        self.delete = delete

    # NT provides delete-on-close as a primitive, so we don't need
    # the wrapper to do anything special.  We still use it so that
    # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
    if _os.name != 'nt':
        # Cache the unlinker so we don't get spurious errors at
        # shutdown when the module-level "os" is None'd out.  Note
        # that this must be referenced as self.unlink, because the
        # name TemporaryFileWrapper may also get None'd out before
        # __del__ is called.

439 440
        def close(self, unlink=_os.unlink):
            if not self.close_called and self.file is not None:
441
                self.close_called = True
442 443 444 445 446
                try:
                    self.file.close()
                finally:
                    if self.delete:
                        unlink(self.name)
447 448 449 450 451 452 453 454 455 456 457 458

        # Need to ensure the file is deleted on __del__
        def __del__(self):
            self.close()

    else:
        def close(self):
            if not self.close_called:
                self.close_called = True
                self.file.close()


459 460 461 462 463 464 465
class _TemporaryFileWrapper:
    """Temporary file wrapper

    This class provides a wrapper around files opened for
    temporary use.  In particular, it seeks to automatically
    remove the file when it is no longer needed.
    """
466

467
    def __init__(self, file, name, delete=True):
468 469
        self.file = file
        self.name = name
470
        self.delete = delete
471
        self._closer = _TemporaryFileCloser(file, name, delete)
472 473

    def __getattr__(self, name):
Christian Heimes's avatar
Christian Heimes committed
474 475 476
        # Attribute lookups are delegated to the underlying file
        # and cached for non-numeric results
        # (i.e. methods are cached, closed and friends are not)
477 478
        file = self.__dict__['file']
        a = getattr(file, name)
479 480 481 482 483 484 485 486 487
        if hasattr(a, '__call__'):
            func = a
            @_functools.wraps(func)
            def func_wrapper(*args, **kwargs):
                return func(*args, **kwargs)
            # Avoid closing the file as long as the wrapper is alive,
            # see issue #18879.
            func_wrapper._closer = self._closer
            a = func_wrapper
Christian Heimes's avatar
Christian Heimes committed
488
        if not isinstance(a, int):
489
            setattr(self, name, a)
490
        return a
491

Christian Heimes's avatar
Christian Heimes committed
492 493 494 495 496 497
    # The underlying __enter__ method returns the wrong object
    # (self.file) so override it to return the wrapper
    def __enter__(self):
        self.file.__enter__()
        return self

498 499 500 501 502 503 504 505 506 507 508 509 510
    # Need to trap __exit__ as well to ensure the file gets
    # deleted when used in a with statement
    def __exit__(self, exc, value, tb):
        result = self.file.__exit__(exc, value, tb)
        self.close()
        return result

    def close(self):
        """
        Close the temporary file, possibly deleting it.
        """
        self._closer.close()

Christian Heimes's avatar
Christian Heimes committed
511
    # iter() doesn't use __getattr__ to find the __iter__ method
512
    def __iter__(self):
513
        # Don't return iter(self.file), but yield from it to avoid closing
514 515 516 517
        # file as long as it's being used as iterator (see issue #23700).  We
        # can't use 'yield from' here because iter(file) returns the file
        # object itself, which has a close method, and thus the file would get
        # closed when the generator is finalized, due to PEP380 semantics.
518 519
        for line in self.file:
            yield line
520

Christian Heimes's avatar
Christian Heimes committed
521

522
def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None,
523
                       newline=None, suffix=None, prefix=None,
524
                       dir=None, delete=True):
525 526 527
    """Create and return a temporary file.
    Arguments:
    'prefix', 'suffix', 'dir' -- as for mkstemp.
528 529 530 531
    'mode' -- the mode argument to io.open (default "w+b").
    'buffering' -- the buffer size argument to io.open (default -1).
    'encoding' -- the encoding argument to io.open (default None)
    'newline' -- the newline argument to io.open (default None)
532
    'delete' -- whether the file is deleted on close (default True).
533 534
    The file is created as mkstemp() would do it.

535
    Returns an object with a file-like interface; the name of the file
536 537
    is accessible as its 'name' attribute.  The file will be automatically
    deleted when it is closed unless the 'delete' argument is set to False.
538
    """
539

540
    prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
541

542
    flags = _bin_openflags
543

544 545
    # Setting O_TEMPORARY in the flags causes the OS to delete
    # the file when it is closed.  This is only supported by Windows.
546
    if _os.name == 'nt' and delete:
547
        flags |= _os.O_TEMPORARY
548

549
    (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type)
550 551 552
    try:
        file = _io.open(fd, mode, buffering=buffering,
                        newline=newline, encoding=encoding)
553

554
        return _TemporaryFileWrapper(file, name, delete)
555 556
    except BaseException:
        _os.unlink(name)
557 558
        _os.close(fd)
        raise
559

560 561 562
if _os.name != 'posix' or _os.sys.platform == 'cygwin':
    # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
    # while it is open.
563
    TemporaryFile = NamedTemporaryFile
564 565

else:
566 567 568 569 570
    # Is the O_TMPFILE flag available and does it work?
    # The flag is set to False if os.open(dir, os.O_TMPFILE) raises an
    # IsADirectoryError exception
    _O_TMPFILE_WORKS = hasattr(_os, 'O_TMPFILE')

571
    def TemporaryFile(mode='w+b', buffering=-1, encoding=None,
572
                      newline=None, suffix=None, prefix=None,
573
                      dir=None):
574 575
        """Create and return a temporary file.
        Arguments:
576
        'prefix', 'suffix', 'dir' -- as for mkstemp.
577 578 579 580
        'mode' -- the mode argument to io.open (default "w+b").
        'buffering' -- the buffer size argument to io.open (default -1).
        'encoding' -- the encoding argument to io.open (default None)
        'newline' -- the newline argument to io.open (default None)
581 582
        The file is created as mkstemp() would do it.

583 584
        Returns an object with a file-like interface.  The file has no
        name, and will cease to exist when it is closed.
585
        """
586
        global _O_TMPFILE_WORKS
587

588
        prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
589

590
        flags = _bin_openflags
591 592 593 594 595
        if _O_TMPFILE_WORKS:
            try:
                flags2 = (flags | _os.O_TMPFILE) & ~_os.O_CREAT
                fd = _os.open(dir, flags2, 0o600)
            except IsADirectoryError:
596 597 598 599 600
                # Linux kernel older than 3.11 ignores the O_TMPFILE flag:
                # O_TMPFILE is read as O_DIRECTORY. Trying to open a directory
                # with O_RDWR|O_DIRECTORY fails with IsADirectoryError, a
                # directory cannot be open to write. Set flag to False to not
                # try again.
601 602 603 604
                _O_TMPFILE_WORKS = False
            except OSError:
                # The filesystem of the directory does not support O_TMPFILE.
                # For example, OSError(95, 'Operation not supported').
605 606 607 608 609
                #
                # On Linux kernel older than 3.11, trying to open a regular
                # file (or a symbolic link to a regular file) with O_TMPFILE
                # fails with NotADirectoryError, because O_TMPFILE is read as
                # O_DIRECTORY.
610 611 612 613 614 615 616 617 618
                pass
            else:
                try:
                    return _io.open(fd, mode, buffering=buffering,
                                    newline=newline, encoding=encoding)
                except:
                    _os.close(fd)
                    raise
            # Fallback to _mkstemp_inner().
619

620
        (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type)
621 622
        try:
            _os.unlink(name)
623 624
            return _io.open(fd, mode, buffering=buffering,
                            newline=newline, encoding=encoding)
625 626 627
        except:
            _os.close(fd)
            raise
628 629

class SpooledTemporaryFile:
630 631
    """Temporary file wrapper, specialized to switch from BytesIO
    or StringIO to a real file when it exceeds a certain size or
632 633 634 635
    when a fileno is needed.
    """
    _rolled = False

636 637
    def __init__(self, max_size=0, mode='w+b', buffering=-1,
                 encoding=None, newline=None,
638
                 suffix=None, prefix=None, dir=None):
639 640 641
        if 'b' in mode:
            self._file = _io.BytesIO()
        else:
642 643
            # Setting newline="\n" avoids newline translation;
            # this is important because otherwise on Windows we'd
644
            # get double newline translation upon rollover().
645
            self._file = _io.StringIO(newline="\n")
646 647
        self._max_size = max_size
        self._rolled = False
648 649 650 651
        self._TemporaryFileArgs = {'mode': mode, 'buffering': buffering,
                                   'suffix': suffix, 'prefix': prefix,
                                   'encoding': encoding, 'newline': newline,
                                   'dir': dir}
652 653 654 655 656 657 658 659 660 661

    def _check(self, file):
        if self._rolled: return
        max_size = self._max_size
        if max_size and file.tell() > max_size:
            self.rollover()

    def rollover(self):
        if self._rolled: return
        file = self._file
662
        newfile = self._file = TemporaryFile(**self._TemporaryFileArgs)
663 664 665 666 667 668 669
        del self._TemporaryFileArgs

        newfile.write(file.getvalue())
        newfile.seek(file.tell(), 0)

        self._rolled = True

Christian Heimes's avatar
Christian Heimes committed
670 671
    # The method caching trick from NamedTemporaryFile
    # won't work here, because _file may change from a
672
    # BytesIO/StringIO instance to a real file. So we list
Christian Heimes's avatar
Christian Heimes committed
673 674 675 676 677 678 679 680 681 682 683
    # all the methods directly.

    # Context management protocol
    def __enter__(self):
        if self._file.closed:
            raise ValueError("Cannot enter context with closed file")
        return self

    def __exit__(self, exc, value, tb):
        self._file.close()

684 685 686 687 688 689 690 691 692 693 694 695 696
    # file protocol
    def __iter__(self):
        return self._file.__iter__()

    def close(self):
        self._file.close()

    @property
    def closed(self):
        return self._file.closed

    @property
    def encoding(self):
697 698 699 700 701 702
        try:
            return self._file.encoding
        except AttributeError:
            if 'b' in self._TemporaryFileArgs['mode']:
                raise
            return self._TemporaryFileArgs['encoding']
703 704 705 706 707 708 709 710 711 712 713 714 715

    def fileno(self):
        self.rollover()
        return self._file.fileno()

    def flush(self):
        self._file.flush()

    def isatty(self):
        return self._file.isatty()

    @property
    def mode(self):
716 717 718 719
        try:
            return self._file.mode
        except AttributeError:
            return self._TemporaryFileArgs['mode']
720 721 722

    @property
    def name(self):
723 724 725 726
        try:
            return self._file.name
        except AttributeError:
            return None
727 728 729

    @property
    def newlines(self):
730 731 732 733 734 735
        try:
            return self._file.newlines
        except AttributeError:
            if 'b' in self._TemporaryFileArgs['mode']:
                raise
            return self._TemporaryFileArgs['newline']
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755

    def read(self, *args):
        return self._file.read(*args)

    def readline(self, *args):
        return self._file.readline(*args)

    def readlines(self, *args):
        return self._file.readlines(*args)

    def seek(self, *args):
        self._file.seek(*args)

    @property
    def softspace(self):
        return self._file.softspace

    def tell(self):
        return self._file.tell()

756 757 758 759 760 761 762
    def truncate(self, size=None):
        if size is None:
            self._file.truncate()
        else:
            if size > self._max_size:
                self.rollover()
            self._file.truncate(size)
763 764 765 766 767 768 769 770 771 772 773 774 775

    def write(self, s):
        file = self._file
        rv = file.write(s)
        self._check(file)
        return rv

    def writelines(self, iterable):
        file = self._file
        rv = file.writelines(iterable)
        self._check(file)
        return rv

776 777 778 779 780 781 782 783 784

class TemporaryDirectory(object):
    """Create and return a temporary directory.  This has the same
    behavior as mkdtemp but can be used as a context manager.  For
    example:

        with TemporaryDirectory() as tmpdir:
            ...

785
    Upon exiting the context, the directory and everything contained
786 787 788
    in it are removed.
    """

789
    def __init__(self, suffix=None, prefix=None, dir=None):
790
        self.name = mkdtemp(suffix, prefix, dir)
791 792 793 794 795
        self._finalizer = _weakref.finalize(
            self, self._cleanup, self.name,
            warn_message="Implicitly cleaning up {!r}".format(self))

    @classmethod
796
    def _cleanup(cls, name, warn_message):
797
        _shutil.rmtree(name)
798
        _warnings.warn(warn_message, ResourceWarning)
799

800 801
    def __repr__(self):
        return "<{} {!r}>".format(self.__class__.__name__, self.name)
802 803 804 805 806 807 808

    def __enter__(self):
        return self.name

    def __exit__(self, exc, value, tb):
        self.cleanup()

809
    def cleanup(self):
810
        if self._finalizer.detach():
811
            _shutil.rmtree(self.name)