How to set the working directory for a Python subprocess (cwd)
Codemia Knowledge Hub ·
Pass the cwd parameter to subprocess.run(), subprocess.Popen(), or any other subprocess function. The child process runs in that directory, and your main Python process keeps its own working directory.
The command runs as if you had done cd /tmp first, but your Python process stays where it was.
Why cwd beats os.chdir()
os.chdir() before launching the subprocess also works, but it changes the working directory of the whole Python process, affecting every later file operation, not just the subprocess.
cwd is scoped to the child only:
| Approach | Affects parent process | Affects child process | Thread-safe |
cwd parameter | No | Yes | Yes |
os.chdir() | Yes (global) | Yes (inherited) | No (process-wide state) |
In multi-threaded applications, os.chdir() is particularly dangerous because it changes the directory for every thread at once.
cwd with subprocess.run()
subprocess.run() is the recommended high-level function for most cases.
Running a build command in a project directory
Running a git command in a specific repository
Windows example
With shell=True on Windows, the command runs through cmd.exe. cwd still works, but relative paths can behave differently because cmd.exe has its own path resolution rules.
Use check=True unless you have a reason to handle failure yourself. Without it, a subprocess that exits non-zero returns normally and your code carries on as if nothing went wrong; with it, you get CalledProcessError.
cwd with subprocess.Popen()
For long-running processes or streaming output, Popen takes the same cwd parameter:
Streaming output with error handling
Setting cwd and env together
env replaces the entire environment, so start from os.environ.copy() and add overrides:
Cross-platform paths with pathlib.Path
Hard-coded string paths are brittle. pathlib.Path produces platform-appropriate paths:
cwd accepts both str and Path objects, so no conversion is needed.
When the cwd directory does not exist
If the directory passed to cwd does not exist, Python raises FileNotFoundError before launching the subprocess. Passing a file path instead of a directory raises NotADirectoryError.
To avoid it, create the directory first:
Telling a missing directory from a missing command
An invalid cwd gives:
A missing command gives:
Both are FileNotFoundError; only the message differs. To distinguish them in code, check whether the exception mentions your cwd:
Relative paths inside the subprocess
With cwd set, every relative path the subprocess uses resolves against that directory, not against your script's location. That is the point of cwd, but it still surprises people while debugging.
If the subprocess reads config/settings.yml, it looks for /tmp/config/settings.yml here. Likewise, writing results/data.csv with cwd="/tmp" produces /tmp/results/data.csv.
Example: running tests in several project directories
Each subprocess.run() call runs in its own directory without interfering with the others or with the parent process.
Related reading
- How can I speed up Python's 'unittest' on multicore machines?
- How can I stop a particular cell from running in google colab?
- How can I strip the whitespace from Pandas DataFrame headers?
- How can I tell if a string repeats itself in Python?
- How can I test lambda in local using python?
- How can I time a code segment for testing performance with Pythons timeit?
- How can I use a conditional expression expression with if and else in a list comprehension?
- How can I use a different version of python during NPM install?
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.