Sub topic 9
Setting the environment and working directory
This chapter assumes you can call subprocess.run and read a CompletedProcess, and that you know what capture_output=True and check=True do. Here you will control two things a child process inherits from its parent: its environment variables and its current working directory.
What a child process inherits
When Python starts a child process, the operating system gives the child two pieces of context besides its arguments:
- The environment. This is a set of name and value string pairs such as
PATH,HOMEandLANG. Programs read it to find tools, locate configuration and choose behavior. - The working directory. This is the folder the child treats as "here". Relative paths such as
data.csvor./buildare resolved against it.
By default the child gets a copy of the parent's environment and starts in the parent's working directory. Two arguments to subprocess.run (and to Popen) override this:
env=replaces the child's entire environment.cwd=sets the directory the child starts in.
Neither argument changes anything in your own Python process. They affect only the child.
Adding a variable with `env`
The most common mistake is to treat env as "extra variables to add". It is not. It is the complete environment. To add one variable, copy the current environment and add to 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 containing every current variable plus GREETING. If the parent already had a GREETING, the later entry wins. The child prints hi and the temporary directory (on macOS this may appear as a /private/... path).
What happens when you replace the environment
Passing a small dictionary on its own gives the child a very small environment:
import subprocess
import sys
result = subprocess.run(
[sys.executable, "-c", "import os; print('PATH' in os.environ)"],
env={"ONLY": "1"},
capture_output=True,
text=True,
check=True,
)
print(result.stdout.strip())On Linux and macOS this prints False. The child has no PATH, so it cannot find programs by bare name, and it has no HOME, LANG or TMPDIR either. The consequences depend on the program:
- A shell script that calls
gitorlsby name may fail with "command not found". - Tools that read
HOMEmay write config files to unexpected places or fail. - On Windows, a child without
SystemRootcan fail in odd ways, because networking and cryptography libraries depend on it.
A minimal environment is useful on purpose, for example in tests that must not depend on the developer's machine or to keep secrets out of a child. In that case, keep the variables the child needs and nothing else, and test it.
Building the environment safely
Three habits prevent most environment bugs.
Copy, then change the copy. Use os.environ.copy() or {**os.environ}. Do not write into os.environ itself to configure one child. That changes your whole process, affects every thread and every later child, and makes behavior depend on call order.
Use strings only. The environment holds strings. A number or None raises TypeError when the child is started:
import os
import subprocess
import sys
env = os.environ.copy()
env["PORT"] = str(8080) # PORT = 8080 would raise TypeError
env.pop("DEBUG", None) # remove a variable if it is present, no error if not
result = subprocess.run(
[sys.executable, "-c", "import os; print(os.environ['PORT'], os.environ.get('DEBUG'))"],
env=env,
capture_output=True,
text=True,
check=True,
)
print(result.stdout.strip())This prints 8080 None. Use pop with a default to remove variables. Setting a value to None or an empty string is not the same as removing it. A variable set to an empty string still exists, and some programs treat "set but empty" differently from "unset".
Wrap the pattern in a helper. When several calls need the same setup, put the rules in one place:
import os
import subprocess
import sys
import tempfile
from pathlib import Path
def run_in(directory, extra_env=None, drop=()):
env = os.environ.copy()
env.update(extra_env or {})
for name in drop:
env.pop(name, None)
script = (
"import os; "
"print(os.getcwd()); "
"print(os.environ.get('MODE')); "
"print(os.environ.get('DEBUG'))"
)
return subprocess.run(
[sys.executable, "-c", script],
env=env,
cwd=directory,
capture_output=True,
text=True,
check=True,
)
result = run_in(Path(tempfile.gettempdir()), {"MODE": "test"}, drop=("DEBUG",))
print(result.stdout)The child sees MODE set to test and DEBUG unset, whatever the parent had. Note that cwd accepts a pathlib.Path as well as a string.
Choosing the working directory with `cwd`
Many tools behave according to where they run. git status reports on the repository containing the current directory, make looks for a Makefile there, and npm install reads package.json there. Passing cwd is the clean way to run these in a chosen folder:
import subprocess
from pathlib import Path
repo = Path.home()
result = subprocess.run(
["git", "rev-parse", "--show-toplevel"],
cwd=repo,
capture_output=True,
text=True,
)
print(result.returncode, result.stdout.strip() or result.stderr.strip())This runs git as if you had typed cd into the folder first. It does not call os.chdir, so your own process stays where it was. That matters in programs with several threads or tasks, because the working directory is process-wide state that one os.chdir would change for all of them.
The directory must exist
If cwd does not exist, the child cannot be started, and Python raises an OSError subclass before running anything:
import subprocess
import sys
try:
subprocess.run([sys.executable, "-c", "pass"], cwd="/no/such/dir")
except OSError as exc:
print("could not start:", exc)On Linux and macOS the error is FileNotFoundError. The message names the directory, but it looks the same as the error for a missing program, so check both when you see it. On Windows the error type can differ, which is why this example catches OSError, the parent class.
Relative paths: who resolves them
cwd changes how the child resolves relative paths, but Python does not rewrite your arguments. Consider this call:
subprocess.run(["wc", "-l", "notes.txt"], cwd="/home/ana/project")The string notes.txt is passed unchanged to wc, and wc looks for it in /home/ana/project. Your Python process never opens the file, so Python's own working directory is irrelevant to it.
Relative program names are the one place where cwd also affects Python. If the program path contains a directory part, such as ./build/tool, it is interpreted relative to cwd on POSIX systems. A bare name like git is searched for on PATH. Two habits keep this predictable: build absolute paths with Path.resolve() before the call, and use sys.executable when you want to run the same Python as the parent.
Interaction between `env` and program lookup
On POSIX systems, if you pass env, a bare program name such as git is searched using the PATH from that env mapping. If your minimal environment has no PATH, the lookup uses a built-in default path, which may not include where your tool lives, and you get FileNotFoundError. Windows resolves program names differently, so code that depends on this should be tested on each system you support. The simplest fix on every system is to pass the full path to the executable, or to keep PATH in the environment.
Quick reference
| Goal | How |
|---|---|
| Add or override a variable | `env={**os.environ, "NAME": "value"}` |
| Remove a variable | Copy `os.environ`, then `env.pop("NAME", None)` |
| Run with a minimal environment | `env={"PATH": "/usr/bin"}`, plus anything the tool needs |
| Run in another folder | `cwd="/some/dir"` or a `Path` |
| Keep your own process unchanged | Use `env` and `cwd`, not `os.environ[...]` or `os.chdir` |
| Values that are not text | Convert with `str(...)` first |
Exercise
A script runs subprocess.run(["make", "build"], env={"CI": "1"}, cwd="/srv/app"). It works on the developer's laptop but fails on a server with "make: command not found". The Makefile is in /srv/app and make is installed. What is wrong, and how do you fix it?
Show answer
The env argument replaces the whole environment, so the child has no PATH (and no HOME or LANG). On POSIX the bare name make is searched in the PATH from env, so the lookup fails or falls back to a default that may not include make. Fix it by copying the parent environment and adding the variable: env={**os.environ, "CI": "1"}. Alternatively keep a PATH entry in the dictionary, or pass the full path to make. The cwd argument is correct and needs no change.