Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f1512a2

Browse files
author
Victor Stinner
committed
Close #12383: Fix subprocess module with env={}: don't copy the environment
variables, start with an empty environment.
1 parent b7149ca commit f1512a2

3 files changed

Lines changed: 20 additions & 8 deletions

File tree

Lib/subprocess.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1169,7 +1169,7 @@ def _execute_child(self, args, executable, preexec_fn, close_fds,
11691169
# potential deadlocks, thus we do all this here.
11701170
# and pass it to fork_exec()
11711171

1172-
if env:
1172+
if env is not None:
11731173
env_list = [os.fsencode(k) + b'=' + os.fsencode(v)
11741174
for k, v in env.items()]
11751175
else:

Lib/test/test_subprocess.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -331,13 +331,22 @@ def test_cwd(self):
331331
def test_env(self):
332332
newenv = os.environ.copy()
333333
newenv["FRUIT"] = "orange"
334-
p = subprocess.Popen([sys.executable, "-c",
335-
'import sys,os;'
336-
'sys.stdout.write(os.getenv("FRUIT"))'],
337-
stdout=subprocess.PIPE,
338-
env=newenv)
339-
self.addCleanup(p.stdout.close)
340-
self.assertEqual(p.stdout.read(), b"orange")
334+
with subprocess.Popen([sys.executable, "-c",
335+
'import sys,os;'
336+
'sys.stdout.write(os.getenv("FRUIT"))'],
337+
stdout=subprocess.PIPE,
338+
env=newenv) as p:
339+
stdout, stderr = p.communicate()
340+
self.assertEqual(stdout, b"orange")
341+
342+
def test_empty_env(self):
343+
with subprocess.Popen([sys.executable, "-c",
344+
'import os; '
345+
'print(len(os.environ))'],
346+
stdout=subprocess.PIPE,
347+
env={}) as p:
348+
stdout, stderr = p.communicate()
349+
self.assertEqual(stdout.strip(), b"0")
341350

342351
def test_communicate_stdin(self):
343352
p = subprocess.Popen([sys.executable, "-c",

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@ Core and Builtins
2525
Library
2626
-------
2727

28+
- Issue #12383: Fix subprocess module with env={}: don't copy the environment
29+
variables, start with an empty environment.
30+
2831
- Issue #11584: email.header.decode_header no longer fails if the header
2932
passed to it is a Header object, and Header/make_header no longer fail
3033
if given binary unknown-8bit input.

0 commit comments

Comments
 (0)