Python Process Environment and Working Directory
A child process starts with a copy of your environment and your working directory. Both can be set per child, and both have a trap: env= replaces the whole environment rather than adding to it, so a child given one variable has no HOME and a PATH it did not expect; and os.chdir changes the directory for everything after it, whereas cwd= affects only that one child.
OS and Process Automation Guide 19 of 39 Intermediate
- Control nodeUbuntu 26.04 LTS
- Python3.14.4
- requests2.34.2
- paramiko5.0.0
- TimeAbout 15 min
Nothing on this page is version-dependent. os.environ has behaved this way since Python 2 and cwd= has been a subprocess argument from the start.
- pytest9.1.1
- PyYAML6.0.3
- boto3 / botocore1.43.78
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| RUNNER01 | 192.168.0.27 | Ubuntu 26.04 LTS | Control node - every script in this path runs here | 2 Core | 4 GB | 50 GB |
This guide includes
Use this before spawning anything. This matters because env= replaces the environment rather than adding to it - so a child given one variable loses PATH and everything else it needed.
- seeing a child inherit the environment
- meeting the trap in
env=, which replaces rather than adds - finding what working directory a child gets
- preferring
cwd=toos.chdir - asking what a process knows about itself
Before you start
-
A child inherits the environment
-
env= replaces rather than adds
-
The working directory a child gets
-
So prefer cwd= over os.chdir
-
What a process knows about itself