Python subprocess.run: Give One Child Its Own Proxy Environment
Pass a copied environment to subprocess.run when one child command needs a proxy without changing Python's environment for other work.
A Python program can give one child command its own proxy environment. Copy the inherited values, change the copy, and pass it to subprocess.run:
import os
import subprocess
child_env = os.environ.copy()
child_env["https_proxy"] = "http://proxy.example:8080"
subprocess.run(
["curl", "--head", "https://www.example.com/"],
env=child_env,
check=True,
timeout=30,
)
The example assumes curl is already available. Its HTTPS request can use an HTTP proxy that supports the required tunnel. For this public-site check with no proxy credentials configured, a candidate from the HTTP proxy list can replace the example endpoint. The child still receives the rest of the copied environment, including any applicable bypass settings.
Passing env gives this invocation that environment. The copy avoids changing os.environ for other work in the Python process.
Assigning to os.environ directly is also meaningful: it updates Python's process environment and can affect children started afterward. It does not update the shell that launched Python, an unrelated application, or a child that is already running.
If the intention is to change future commands in your interactive shell, make that change in the shell. If only one launched tool needs a different route, keep its environment next to the subprocess invocation as shown.