brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: contextlib.chdir changes directory and always changes back

Scripting
~/tips/tip-python-contextlib-chdir

from contextlib import chdir

Temporarily changes the working directory for a block and restores it afterwards.

The classic pattern for running something in another directory is os.chdir() plus a try/finally to go back. Python 3.11 added a context manager that does the going back for you.

contextlib.chdir(path) changes the working directory on entry and restores the old one on exit, even when the block raises an exception:

from contextlib import chdir
import subprocess

with chdir("/mnt/user/appdata/<app>"):
    subprocess.run(["git", "pull"])

A quick check shows the restore works. Raise an error inside a nested with chdir("/"), catch it outside, and os.getcwd() is back at the directory of the outer block. The docs say the context manager is reentrant, so nesting is fine.

The caveat is a real one: the working directory belongs to the whole process. The docs call it not parallel-safe and say it is not suitable for most threaded or async code. They add that it is also unsuitable for generators, where execution is paused, and that you should not yield while it is active. A second thread that opens a relative path while another thread sits inside the block would look in the wrong place.

For a single subprocess you do not need it at all. Pass cwd= to subprocess.run and the parent process keeps its directory. In the example above that would be subprocess.run(["git", "pull"], cwd="/mnt/user/appdata/<app>"). I reach for chdir when several calls in a row, or code that only knows relative paths, need the same directory.

Further reading: contextlib.chdir

More Scripting tips import difflib $r = Invoke-RestMethod https://api.github.com/repos/PowerShell/PowerShell/releases/latest import json, os, tempfile from collections import Counter import shutil All Scripting tips (10) All topics

Link