Skip to content

Commit 923056b

Browse files
authored
gh-74389: gh-70560: subprocess.Popen.communicate() now ignores stdin.flush error when closed (GH-142061)
gh-70560: gh-74389: subprocess.Popen.communicate() now ignores stdin.flush error when closed with a unittest and news entry.
1 parent cc6bc4c commit 923056b

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

Lib/subprocess.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2077,6 +2077,10 @@ def _communicate(self, input, endtime, orig_timeout):
20772077
self.stdin.flush()
20782078
except BrokenPipeError:
20792079
pass # communicate() must ignore BrokenPipeError.
2080+
except ValueError:
2081+
# ignore ValueError: I/O operation on closed file.
2082+
if not self.stdin.closed:
2083+
raise
20802084
if not input:
20812085
try:
20822086
self.stdin.close()

Lib/test/test_subprocess.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1104,6 +1104,19 @@ def test_writes_before_communicate(self):
11041104
self.assertEqual(stdout, b"bananasplit")
11051105
self.assertEqual(stderr, b"")
11061106

1107+
def test_communicate_stdin_closed_before_call(self):
1108+
# gh-70560, gh-74389: stdin.close() before communicate()
1109+
# should not raise ValueError from stdin.flush()
1110+
with subprocess.Popen([sys.executable, "-c",
1111+
'import sys; sys.exit(0)'],
1112+
stdin=subprocess.PIPE,
1113+
stdout=subprocess.PIPE,
1114+
stderr=subprocess.PIPE) as p:
1115+
p.stdin.close() # Close stdin before communicate
1116+
# This should not raise ValueError
1117+
(stdout, stderr) = p.communicate()
1118+
self.assertEqual(p.returncode, 0)
1119+
11071120
def test_universal_newlines_and_text(self):
11081121
args = [
11091122
sys.executable, "-c",
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
When the stdin being used by a :class:`subprocess.Popen` instance is closed,
2+
this is now ignored in :meth:`subprocess.Popen.communicate` instead of
3+
leaving the class in an inconsistent state.

0 commit comments

Comments
 (0)