Prepare and enter a temporary directory, cleanup when done
()
| 211 | |
| 212 | @contextlib.contextmanager |
| 213 | def tmp_chdir() -> Iterator[str]: |
| 214 | "Prepare and enter a temporary directory, cleanup when done" |
| 215 | |
| 216 | # Threadsafe |
| 217 | with tmp_chdir_lock: |
| 218 | olddir = os.getcwd() |
| 219 | try: |
| 220 | tmpdir = tempfile.mkdtemp() |
| 221 | os.chdir(tmpdir) |
| 222 | yield tmpdir |
| 223 | finally: |
| 224 | os.chdir(olddir) |
| 225 | shutil.rmtree(tmpdir) |
| 226 | |
| 227 | |
| 228 | # cf http://bugs.python.org/issue26689 |