Skip to content

Commit 604faba

Browse files
SethMichaelLarson1st1
authored andcommitted
bpo-29704: Fix asyncio.SubprocessStreamProtocol closing (#405)
1 parent 13802a3 commit 604faba

File tree

3 files changed

+824
-2
lines changed

3 files changed

+824
-2
lines changed

Diff for: Lib/asyncio/subprocess.py

+15-2
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ def __init__(self, limit, loop):
2424
self._limit = limit
2525
self.stdin = self.stdout = self.stderr = None
2626
self._transport = None
27+
self._process_exited = False
28+
self._pipe_fds = []
2729

2830
def __repr__(self):
2931
info = [self.__class__.__name__]
@@ -43,12 +45,14 @@ def connection_made(self, transport):
4345
self.stdout = streams.StreamReader(limit=self._limit,
4446
loop=self._loop)
4547
self.stdout.set_transport(stdout_transport)
48+
self._pipe_fds.append(1)
4649

4750
stderr_transport = transport.get_pipe_transport(2)
4851
if stderr_transport is not None:
4952
self.stderr = streams.StreamReader(limit=self._limit,
5053
loop=self._loop)
5154
self.stderr.set_transport(stderr_transport)
55+
self._pipe_fds.append(2)
5256

5357
stdin_transport = transport.get_pipe_transport(0)
5458
if stdin_transport is not None:
@@ -86,9 +90,18 @@ def pipe_connection_lost(self, fd, exc):
8690
else:
8791
reader.set_exception(exc)
8892

93+
if fd in self._pipe_fds:
94+
self._pipe_fds.remove(fd)
95+
self._maybe_close_transport()
96+
8997
def process_exited(self):
90-
self._transport.close()
91-
self._transport = None
98+
self._process_exited = True
99+
self._maybe_close_transport()
100+
101+
def _maybe_close_transport(self):
102+
if len(self._pipe_fds) == 0 and self._process_exited:
103+
self._transport.close()
104+
self._transport = None
92105

93106

94107
class Process:

Diff for: Lib/test/test_asyncio/test_subprocess.py

+24
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,30 @@ def test_popen_error(self):
459459
self.loop.run_until_complete(create)
460460
self.assertEqual(warns, [])
461461

462+
def test_read_stdout_after_process_exit(self):
463+
@asyncio.coroutine
464+
def execute():
465+
code = '\n'.join(['import sys',
466+
'for _ in range(64):',
467+
' sys.stdout.write("x" * 4096)',
468+
'sys.stdout.flush()',
469+
'sys.exit(1)'])
470+
471+
fut = asyncio.create_subprocess_exec(
472+
sys.executable, '-c', code,
473+
stdout=asyncio.subprocess.PIPE,
474+
loop=self.loop)
475+
476+
process = yield from fut
477+
while True:
478+
data = yield from process.stdout.read(65536)
479+
if data:
480+
yield from asyncio.sleep(0.3, loop=self.loop)
481+
else:
482+
break
483+
484+
self.loop.run_until_complete(execute())
485+
462486

463487
if sys.platform != 'win32':
464488
# Unix

0 commit comments

Comments
 (0)