New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
subprocess.run: add an extra_env kwarg to complement existing env kwarg #84038
Comments
a common idiom i run into is wanting to add/set one or two env vars when running a command via subprocess. the only thing the API allows currently is inherting the current environment, or specifying the complete environment. this means a lot of copying & pasting of the pattern: env = os.environ.copy()
env['FOO'] = ...
env['BAR'] = ...
subprocess.run(..., env=env, ...) it would nice if we could simply express this incremental behavior: subprocess.run(..., extra_env={'FOO': ..., 'BAR': ...}, ...) then the subprocess API would take care of copying & merging. if extra_env:
assert env is None
env = os.environ.copy()
env.update(extra_env) this is akin to subprocess.run's capture_output shortcut. it's unclear to me whether this would be in both subprocess.Popen & subprocess.run, or only subprocess.run. it seems like subprocess.Popen elides convenience APIs. |
dict syntax tools make it fairy easy to compose new dicts from old ones with overrides: subprocess.run(..., env={**os.environ, 'FOO': ..., 'BAR', ...}, ...) Would this be sufficient to avoid the copy/pasting boilerplate? |
Caleb's answer, using PEP-584's merge operator: newenv = os.environ | {'FOO': ..., 'BAR': ...}
subprocess.run(..., env=new_env, ...) |
Ah, I didn't realize that os.environ and os.environ b aren't dict subclasses. I've added a ticket to update them with the new operators! |
personally i still like having the extra_env setting explicitly broken out, but i agree that those operators help ease the majority of the pain. i hadn't come across them before as they aren't in Python 2. i wouldn't be upset if people declined the FR considering those options will be available in Python 3.9+. thx for the tips. |
The dict unpacking generalizations that I posted were added in Python 3.5, which is pretty old by now. (But, true, is in Python 3 and not Python 2). This is the PEP: https://www.python.org/dev/peps/pep-0448/ The new syntax that Brandt posted will indeed only be available from 3.9 on. |
I think those dict unpacking and merging options are sufficient that adding an extra_env= parameter would merely complicate the already over complex API. Thanks for the suggestions folks! |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: