subprocess
working directory
programming
Python
software development

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.

python
1import subprocess
2
3result = subprocess.run(
4    ["ls", "-la"],
5    cwd="/tmp",
6    capture_output=True,
7    text=True,
8    check=True,
9)
10print(result.stdout)

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.

python
1import os
2import subprocess
3
4# BAD: changes directory for the entire process
5os.chdir("/tmp")
6subprocess.run(["ls", "-la"])
7
8# Everything after this point now operates in /tmp
9# Opening "config.yml" would look for /tmp/config.yml

cwd is scoped to the child only:

python
1import subprocess
2
3# GOOD: only the subprocess sees /tmp as its working directory
4subprocess.run(["ls", "-la"], cwd="/tmp")
5
6# The Python process is still in its original directory
7# Opening "config.yml" looks in the original location
ApproachAffects parent processAffects child processThread-safe
cwd parameterNoYesYes
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

python
1import subprocess
2from pathlib import Path
3
4project_dir = Path.home() / "projects" / "myapp"
5
6result = subprocess.run(
7    ["make", "build"],
8    cwd=project_dir,
9    capture_output=True,
10    text=True,
11    check=True,
12)
13print(result.stdout)

Running a git command in a specific repository

python
1import subprocess
2
3result = subprocess.run(
4    ["git", "log", "--oneline", "-5"],
5    cwd="/home/dev/my-repo",
6    capture_output=True,
7    text=True,
8    check=True,
9)
10print(result.stdout)

Windows example

python
1import subprocess
2
3result = subprocess.run(
4    ["cmd", "/c", "dir"],
5    cwd=r"C:\Users\dev\project",
6    capture_output=True,
7    text=True,
8    check=True,
9)
10print(result.stdout)

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:

python
1import subprocess
2
3process = subprocess.Popen(
4    ["python", "manage.py", "runserver"],
5    cwd="/home/dev/django-project",
6    stdout=subprocess.PIPE,
7    stderr=subprocess.PIPE,
8    text=True,
9)
10
11# Read output line by line
12for line in process.stdout:
13    print(line, end="")
14
15process.wait()

Streaming output with error handling

python
1import subprocess
2
3process = subprocess.Popen(
4    ["npm", "run", "build"],
5    cwd="/home/dev/frontend",
6    stdout=subprocess.PIPE,
7    stderr=subprocess.STDOUT,  # merge stderr into stdout
8    text=True,
9)
10
11for line in process.stdout:
12    print(f"[build] {line}", end="")
13
14return_code = process.wait()
15if return_code != 0:
16    print(f"Build failed with exit code {return_code}")

Setting cwd and env together

env replaces the entire environment, so start from os.environ.copy() and add overrides:

python
1import os
2import subprocess
3
4env = os.environ.copy()
5env["NODE_ENV"] = "production"
6env["PORT"] = "3000"
7
8result = subprocess.run(
9    ["node", "server.js"],
10    cwd="/home/dev/api",
11    env=env,
12    capture_output=True,
13    text=True,
14    check=True,
15)

Cross-platform paths with pathlib.Path

Hard-coded string paths are brittle. pathlib.Path produces platform-appropriate paths:

python
1from pathlib import Path
2import subprocess
3
4# Construct path relative to the script's location
5script_dir = Path(__file__).resolve().parent
6data_dir = script_dir / "data" / "input"
7
8result = subprocess.run(
9    ["python", "process.py"],
10    cwd=data_dir,
11    capture_output=True,
12    text=True,
13    check=True,
14)

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.

python
1import subprocess
2
3try:
4    subprocess.run(["ls"], cwd="/nonexistent/path", check=True)
5except FileNotFoundError as e:
6    print(f"Directory not found: {e}")

To avoid it, create the directory first:

python
1from pathlib import Path
2import subprocess
3
4workdir = Path("/tmp/my-job-output")
5workdir.mkdir(parents=True, exist_ok=True)
6
7subprocess.run(["pwd"], cwd=workdir, check=True)

Telling a missing directory from a missing command

An invalid cwd gives:

text
FileNotFoundError: [Errno 2] No such file or directory: '/nonexistent/path'

A missing command gives:

text
FileNotFoundError: [Errno 2] No such file or directory: 'nonexistent-command'

Both are FileNotFoundError; only the message differs. To distinguish them in code, check whether the exception mentions your cwd:

python
1import subprocess
2from pathlib import Path
3
4workdir = Path("/tmp/my-job")
5cmd = ["my-tool", "--flag"]
6
7try:
8    subprocess.run(cmd, cwd=workdir, check=True)
9except FileNotFoundError as e:
10    if str(workdir) in str(e):
11        print(f"Working directory does not exist: {workdir}")
12    else:
13        print(f"Command not found: {cmd[0]}")

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.

python
1import subprocess
2
3# The subprocess writes to /tmp/output.txt, not ./output.txt
4subprocess.run(
5    ["bash", "-c", "echo hello > output.txt"],
6    cwd="/tmp",
7    check=True,
8)
9
10# Verify
11result = subprocess.run(
12    ["cat", "output.txt"],
13    cwd="/tmp",
14    capture_output=True,
15    text=True,
16)
17print(result.stdout)  # "hello"

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

python
1import subprocess
2from pathlib import Path
3
4def run_tests(project_path: str, verbose: bool = False) -> bool:
5    """Run pytest in the given project directory."""
6    cmd = ["python", "-m", "pytest"]
7    if verbose:
8        cmd.append("-v")
9
10    result = subprocess.run(
11        cmd,
12        cwd=project_path,
13        capture_output=True,
14        text=True,
15    )
16
17    print(result.stdout)
18    if result.stderr:
19        print(result.stderr)
20
21    return result.returncode == 0
22
23# Run tests in three different projects
24projects = [
25    Path.home() / "projects" / "auth-service",
26    Path.home() / "projects" / "user-service",
27    Path.home() / "projects" / "api-gateway",
28]
29
30for project in projects:
31    success = run_tests(project, verbose=True)
32    status = "PASSED" if success else "FAILED"
33    print(f"{project.name}: {status}\n")

Each subprocess.run() call runs in its own directory without interfering with the others or with the parent process.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No 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 course
Data 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.

Practice algorithms