Return a context manager that changes the current working directory. Arguments: path: the directory to use as the temporary current working directory. quiet: if False (the default), the context manager raises an exception on error. Otherwise, it issues only a warning and
(path, quiet=False)
| 546 | |
| 547 | @contextlib.contextmanager |
| 548 | def change_cwd(path, quiet=False): |
| 549 | """Return a context manager that changes the current working directory. |
| 550 | |
| 551 | Arguments: |
| 552 | |
| 553 | path: the directory to use as the temporary current working directory. |
| 554 | |
| 555 | quiet: if False (the default), the context manager raises an exception |
| 556 | on error. Otherwise, it issues only a warning and keeps the current |
| 557 | working directory the same. |
| 558 | |
| 559 | """ |
| 560 | saved_dir = os.getcwd() |
| 561 | try: |
| 562 | os.chdir(os.path.realpath(path)) |
| 563 | except OSError as exc: |
| 564 | if not quiet: |
| 565 | raise |
| 566 | logging.getLogger(__name__).warning( |
| 567 | 'tests may fail, unable to change the current working directory ' |
| 568 | 'to %r: %s', |
| 569 | path, |
| 570 | exc, |
| 571 | exc_info=exc, |
| 572 | stack_info=True, |
| 573 | stacklevel=3, |
| 574 | ) |
| 575 | try: |
| 576 | yield os.getcwd() |
| 577 | finally: |
| 578 | os.chdir(saved_dir) |
| 579 | |
| 580 | |
| 581 | @contextlib.contextmanager |