cwd context manager
examples/advanced/mycwd.py
import os from contextlib import contextmanager @contextmanager def cwd(path): oldpwd = os.getcwd() os.chdir(path) try: yield finally: os.chdir(oldpwd)
examples/advanced/context_cd.py
import sys import os from mycwd import cwd def do_something(path): with cwd(path): content = os.listdir() if len(content) < 10: return def main(): if len(sys.argv) != 2: exit(f"Usage: {sys.argv[0]} PATH") path = sys.argv[1] print(os.getcwd()) do_something(path) print(os.getcwd()) main()
$ python context_cd.py /tmp /home/gabor/work/slides/python/examples/advanced /home/gabor/work/slides/python/examples/advanced $ python context_cd.py /opt /home/gabor/work/slides/python/examples/advanced /home/gabor/work/slides/python/examples/advanced