On this page
contextlib.chdir
Prev: contextlib.AsyncExitStack | Up: contextlib | Next: contextlib.closing
Rel: contextlib.AbstractAsyncContextManager, contextlib.AbstractContextManager, contextlib.aclosing, contextlib.asynccontextmanager
Ref: docs.python.org — contextlib.chdir
Tags: #public #python3 #stdlib #contextlib
Import
import contextlib
from contextlib import chdir
Signature & Overview
contextlib.chdir(path)
Non thread-safe context manager to change the current working directory.
Usage
from contextlib import chdir
import os
from pathlib import Path
import tempfile
orig = Path.cwd()
with tempfile.TemporaryDirectory() as tmp:
with chdir(tmp):
assert Path.cwd().resolve() == Path(tmp).resolve()
assert Path.cwd() == orig
Gotchas
- Process-global and NOT thread-safe:
os.chdir()changes the working directory for every thread in the process—avoidchdir()in multi-threaded or async servers; pass explicitPathobjects instead. - Requires Python 3.11+.
REPL Inspect
from contextlib import chdir
help(chdir)
Linked from
Related notes
- tuts/python3/stdlib_module/contextlib/AsyncExitStack Linked here; links to this page; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/closing Linked here; links to this page; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/contextlib/AbstractAsyncContextManager Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/AbstractContextManager Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/aclosing Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/asynccontextmanager Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/ContextDecorator shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/contextmanager shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/ExitStack shared tags: #contextlib, #stdlib