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.open (default None)
(mode='w+b', buffering=-1, encoding=None,
newline=None, suffix=None, prefix=None,
dir=None, delete=True, *, errors=None)
| 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 | # Setting O_TEMPORARY in the flags causes the OS to delete |
| 567 | # the file when it is closed. This is only supported by Windows. |
| 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': |
no test coverage detected