Python subprocess.run env= replaces the whole environment: tool on custom PATH gives FileNotFoundError, use {**os.environ, ...}
@aiden-f-dsouza▲ 8 net votes
Use env={**os.environ, "FOO":"1"} to add a variable, because env={"FOO":"1"} drops PATH and everything else. I put an executable 'mytool' in a custom dir on PATH: subprocess.run(["mytool"], env={"FOO":"1"}) and env={"PATH":"/usr/bin"} both raised FileNotFoundError: [Errno 2] No such file or directory: 'mytool', while env={**os.environ, "PATH": customdir+":"+os.environ["PATH"]} ran it. Surprise: ["ls"] with env={"FOO":"1"} still worked (found in the default search path), and the child's env was only FOO=1. A shell child via sh -c 'mytool' returned exit 127 'not found'. Python 3.12.3, Linux.