Return a context manager that creates a temporary directory. Arguments: path: the directory to create temporarily. If omitted or None, defaults to creating a temporary directory using tempfile.mkdtemp. quiet: if False (the default), the context manager raises an exception
(path=None, quiet=False)
| 501 | |
| 502 | @contextlib.contextmanager |
| 503 | def temp_dir(path=None, quiet=False): |
| 504 | """Return a context manager that creates a temporary directory. |
| 505 | |
| 506 | Arguments: |
| 507 | |
| 508 | path: the directory to create temporarily. If omitted or None, |
| 509 | defaults to creating a temporary directory using tempfile.mkdtemp. |
| 510 | |
| 511 | quiet: if False (the default), the context manager raises an exception |
| 512 | on error. Otherwise, if the path is specified and cannot be |
| 513 | created, only a warning is issued. |
| 514 | |
| 515 | """ |
| 516 | import tempfile |
| 517 | dir_created = False |
| 518 | if path is None: |
| 519 | path = tempfile.mkdtemp() |
| 520 | dir_created = True |
| 521 | path = os.path.realpath(path) |
| 522 | else: |
| 523 | try: |
| 524 | os.mkdir(path) |
| 525 | dir_created = True |
| 526 | except OSError as exc: |
| 527 | if not quiet: |
| 528 | raise |
| 529 | logging.getLogger(__name__).warning( |
| 530 | "tests may fail, unable to create temporary directory %r: %s", |
| 531 | path, |
| 532 | exc, |
| 533 | exc_info=exc, |
| 534 | stack_info=True, |
| 535 | stacklevel=3, |
| 536 | ) |
| 537 | if dir_created: |
| 538 | pid = os.getpid() |
| 539 | try: |
| 540 | yield path |
| 541 | finally: |
| 542 | # In case the process forks, let only the parent remove the |
| 543 | # directory. The child has a different process id. (bpo-30028) |
| 544 | if dir_created and pid == os.getpid(): |
| 545 | rmtree(path) |
| 546 | |
| 547 | |
| 548 | @contextlib.contextmanager |
searching dependent graphs…