Create and return a temporary file. Arguments: 'prefix', 'suffix', 'dir' -- as for mkstemp. '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.
(mode='w+b', buffering=-1, encoding=None,
newline=None, suffix=None, prefix=None,
dir=None, *, errors=None)
| 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 | # Linux kernel older than 3.11 ignores the O_TMPFILE flag: |
| 648 | # O_TMPFILE is read as O_DIRECTORY. Trying to open a directory |
| 649 | # with O_RDWR|O_DIRECTORY fails with IsADirectoryError, a |
| 650 | # directory cannot be open to write. Set flag to False to not |
| 651 | # try again. |
| 652 | _O_TMPFILE_WORKS = False |
| 653 | except OSError: |
| 654 | # The filesystem of the directory does not support O_TMPFILE. |
| 655 | # For example, OSError(95, 'Operation not supported'). |
| 656 | # |
| 657 | # On Linux kernel older than 3.11, trying to open a regular |
| 658 | # file (or a symbolic link to a regular file) with O_TMPFILE |
| 659 | # fails with NotADirectoryError, because O_TMPFILE is read as |
| 660 | # O_DIRECTORY. |
| 661 | pass |
| 662 | # Fallback to _mkstemp_inner(). |
| 663 | |
| 664 | fd = None |
no test coverage detected