Function to create and return a unique temporary directory. Parameters ---------- dir : str If ``dir`` is not None, the directory will be created in that directory; otherwise, Python's default temporary directory is used. Returns ------- out : str
(dir=None)
| 376 | |
| 377 | @contextmanager |
| 378 | def tmpdir(dir=None): |
| 379 | """ |
| 380 | Function to create and return a unique temporary directory. |
| 381 | |
| 382 | Parameters |
| 383 | ---------- |
| 384 | dir : str |
| 385 | If ``dir`` is not None, the directory will be created in that directory; otherwise, |
| 386 | Python's default temporary directory is used. |
| 387 | |
| 388 | Returns |
| 389 | ------- |
| 390 | out : str |
| 391 | Path to the temporary directory |
| 392 | |
| 393 | Notes |
| 394 | ----- |
| 395 | This context manager is particularly useful on Windows for opening temporary directories multiple times. |
| 396 | """ |
| 397 | dirname = tempfile.mkdtemp(dir=dir) |
| 398 | |
| 399 | try: |
| 400 | yield dirname |
| 401 | finally: |
| 402 | if os.path.exists(dirname): |
| 403 | if os.path.isdir(dirname): |
| 404 | with suppress(OSError): |
| 405 | shutil.rmtree(dirname) |
| 406 | else: |
| 407 | with suppress(OSError): |
| 408 | os.remove(dirname) |
| 409 | |
| 410 | |
| 411 | @contextmanager |