Skip to content

Commit 774cb71

Browse files
committed
gh-70560: gh-74389: subprocess.Popen.communicate() now ignores stdin.flush error when closed
with a unittest and news entry.
1 parent 526d7a8 commit 774cb71

3 files changed

Lines changed: 20 additions & 0 deletions

File tree

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
@@ -1062,6 +1062,19 @@ def test_writes_before_communicate(self):
10621062
self.assertEqual(stdout, b"bananasplit")
10631063
self.assertEqual(stderr, b"")
10641064

1065+
def test_communicate_stdin_closed_before_call(self):
1066+
# gh-70560, gh-74389: stdin.close() before communicate()
1067+
# should not raise ValueError from stdin.flush()
1068+
with subprocess.Popen([sys.executable, "-c",
1069+
'import sys; sys.exit(0)'],
1070+
stdin=subprocess.PIPE,
1071+
stdout=subprocess.PIPE,
1072+
stderr=subprocess.PIPE) as p:
1073+
p.stdin.close() # Close stdin before communicate
1074+
# This should not raise ValueError
1075+
(stdout, stderr) = p.communicate()
1076+
self.assertEqual(p.returncode, 0)
1077+
10651078
def test_universal_newlines_and_text(self):
10661079
args = [
10671080
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)