Desk Clarity

Everyday document & browser help

Python Subprocess Loses Environment Settings: Decide Whether to Merge Env

By ON Lab · Sources checked November 9, 2026

The env argument defines the child environment rather than a patch to it. Copy the current environment and override selected keys only when inheritance is intended.

Reproduce the boundary in a disposable example

Passing a small env dictionary causes a child process to lose inherited settings.

import os, subprocess, sys
key = "ONLAB_EXAMPLE_PARENT_MARKER"
os.environ[key] = "parent-only"
try:
    code = "import os; print(os.getenv('ONLAB_EXAMPLE_PARENT_MARKER', 'missing'))"
    replaced = subprocess.run([sys.executable, "-c", code],
        env={"ONLAB_EXAMPLE_CHILD_MARKER": "sample"},
        capture_output=True, text=True, check=True)
    merged = os.environ.copy()
    merged["ONLAB_EXAMPLE_CHILD_MARKER"] = "sample"
    inherited = subprocess.run([sys.executable, "-c", code],
        env=merged, capture_output=True, text=True, check=True)
    assert replaced.stdout.strip() == "missing"
    assert inherited.stdout.strip() == "parent-only"
finally:
    del os.environ[key]
print("replacement versus merge verified")

Read the result before changing application code

The child prints one invented, nonsecret marker. Using an absolute interpreter path keeps executable lookup from obscuring the experiment. In real applications, a missing PATH, certificate setting or application variable can create a different visible symptom even though the environment boundary is the same. Inspect the presence of named required keys rather than dumping the full environment.

Choose the behavior your caller needs

Use inheritance plus targeted overrides for a child that needs the caller’s established environment. Use a deliberately minimal environment for an isolation contract, but include everything the child actually needs. Keep the mapping local to the subprocess call instead of mutating shared process state. Verify the child’s exit status and expected output; successful launch alone does not prove it received its required configuration.

Scope and limits

The local example runs on the recorded host and is not a cross-platform launch certification. Windows may require additional system environment variables when constructing an environment from scratch.

Related: compare the adjacent data or execution boundary.

The embedded example was executed in an isolated local Python process on November 9, 2026. It is a reproducible boundary check, not a test of your full application.

Sources