Sub topic 9
Setting the environment and working directory
This chapter assumes you can call subprocess.run, capture output, and handle CalledProcessError. Here you control two things a child process inherits from your program: its environment variables and its working directory.
What a child inherits
By default, a child process gets a copy of the parent's environment variables and starts in the parent's current working directory. Changes the child makes never affect the parent. Two arguments to subprocess.run override these defaults:
envreplaces the child's environment with the mapping you give it.cwdsets the directory the child starts in.
Adding a variable with env
The env argument replaces the whole environment. It does not add to it. To add one variable, copy the current environment and extend the copy.
import os
import subprocess
import sys
import tempfile
result = subprocess.run(
[sys.executable, "-c", "import os; print(os.environ['GREETING']); print(os.getcwd())"],
env={**os.environ, "GREETING": "hi"},
cwd=tempfile.gettempdir(),
capture_output=True,
text=True,
check=True,
)
print(result.stdout)The expression {**os.environ, "GREETING": "hi"} builds a new dictionary with every current variable plus GREETING. The child prints hi, then the temporary directory path. Your own os.environ stays unchanged.
Setting the working directory with cwd
cwd changes the directory for the child only. This is safer than calling os.chdir in your program, because os.chdir changes the directory for the whole process, including other threads.
The cwd value can be a string or a pathlib.Path. If the directory does not exist, run raises FileNotFoundError before the program starts.
A relative program name is a subtle case. On POSIX systems (Linux and macOS), a relative path in the command list, such as ./tool, is resolved against the new cwd. A bare name such as git is searched on PATH. Use absolute paths for programs you ship with your project.
Replacing the environment completely
Sometimes you want a minimal, predictable environment, for example when testing. Pass only the variables you want.
import subprocess
import sys
result = subprocess.run(
[sys.executable, "-c", "import os; print(sorted(os.environ))"],
env={"ONLY": "this"},
capture_output=True,
text=True,
check=True,
)
print(result.stdout)On Linux and macOS this usually prints ['ONLY']. Be careful, because a stripped environment can break programs that need PATH, HOME, or on Windows SystemRoot. If the child fails mysteriously with an empty environment, copy the variables it needs from os.environ.
Removing a variable
To remove one variable, copy the environment and delete the key.
import os
clean_env = os.environ.copy()
clean_env.pop("PYTHONPATH", None)Pass clean_env as env. Using pop with a default of None avoids a KeyError when the variable is not set.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| `env={"GREETING": "hi"}` when you meant to add a variable | The child loses `PATH` and other variables | Use `{**os.environ, "GREETING": "hi"}` |
| Non-string values such as `{"PORT": 8080}` | `TypeError` | Convert values with `str(8080)` |
| Using `os.chdir` to run a command elsewhere | Changes the directory for your whole program | Use `cwd` |
| Passing a missing `cwd` | `FileNotFoundError` | Check that the directory exists first |
Exercise
A script calls subprocess.run(["git", "status"], env={"LANG": "C"}) and git cannot be found on some machines. What is the likely cause, and how do you fix it while still setting LANG?
Show answer
The env argument replaced the entire environment, so PATH is missing and the system cannot locate git. Copy the current environment and add the variable: env={**os.environ, "LANG": "C"}.
Exercise
Write the argument you would pass to subprocess.run so a child process starts in the folder "build" inside your current directory, without changing your own program's working directory.
Show answer
Pass cwd="build" (or cwd=pathlib.Path("build")). The child starts in that folder, and your program's own directory is unchanged.