Skip to content

Commit a3ea5d2

Browse files
gh-162217: Fix InvalidStateError when subprocess stdin is closed after a cancelled wait_closed() (#162317)
1 parent 89d78fc commit a3ea5d2

3 files changed

Lines changed: 37 additions & 7 deletions

File tree

‎Lib/asyncio/subprocess.py‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -77,13 +77,14 @@ def pipe_connection_lost(self, fd, exc):
7777
if pipe is not None:
7878
pipe.close()
7979
self.connection_lost(exc)
80-
if exc is None:
81-
self._stdin_closed.set_result(None)
82-
else:
83-
self._stdin_closed.set_exception(exc)
84-
# Since calling `wait_closed()` is not mandatory,
85-
# we shouldn't log the traceback if this is not awaited.
86-
self._stdin_closed._log_traceback = False
80+
if not self._stdin_closed.done():
81+
if exc is None:
82+
self._stdin_closed.set_result(None)
83+
else:
84+
self._stdin_closed.set_exception(exc)
85+
# Since calling `wait_closed()` is not mandatory,
86+
# we shouldn't log the traceback if this is not awaited.
87+
self._stdin_closed._log_traceback = False
8788
return
8889
if fd == 1:
8990
reader = self.stdout

‎Lib/test/test_asyncio/test_subprocess.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,31 @@ async def write_stdin(proc, data):
435435
self.loop.run_until_complete, coro)
436436
self.loop.run_until_complete(proc.wait())
437437

438+
def test_stdin_wait_closed_cancelled(self):
439+
# gh-162217: cancelling a task waiting in stdin.wait_closed() must
440+
# not make pipe_connection_lost() fail with InvalidStateError.
441+
async def main():
442+
proc = await asyncio.create_subprocess_exec(
443+
*PROGRAM_CAT,
444+
stdin=subprocess.PIPE,
445+
stdout=subprocess.DEVNULL,
446+
)
447+
try:
448+
task = asyncio.create_task(proc.stdin.wait_closed())
449+
await asyncio.sleep(0)
450+
task.cancel()
451+
with self.assertRaises(asyncio.CancelledError):
452+
await task
453+
finally:
454+
proc.stdin.close()
455+
await proc.wait()
456+
457+
messages = []
458+
self.loop.set_exception_handler(lambda loop, ctx: messages.append(ctx))
459+
460+
self.loop.run_until_complete(main())
461+
self.assertEqual(messages, [])
462+
438463
def test_communicate_ignore_broken_pipe(self):
439464
# buffer large enough to feed the whole pipe buffer
440465
large_data = b'x' * support.PIPE_MAX_SIZE
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Fix :exc:`asyncio.InvalidStateError` being logged when the standard input of
2+
an :mod:`asyncio` subprocess is closed after a task waiting in
3+
:meth:`proc.stdin.wait_closed() <asyncio.StreamWriter.wait_closed>` was
4+
cancelled.

0 commit comments

Comments
 (0)