Skip to content

gh-130925: Add close() method to asyncio.StreamReader #130929

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions Doc/library/asyncio-stream.rst
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,24 @@ StreamReader
Return ``True`` if the buffer is empty and :meth:`feed_eof`
was called.

.. method:: close()

Invoke ``close()`` on the underlying asyncio transport (if one exists).

Note: It is not necessary for code that is given an already
instantiated :class:`StreamReader` instance to call ``close()``
for the sake of cleaning up resources when it is done using
it. Cleanup of the underlying transport is the
reponsibility of the code that provided the
:class:`StreamReader` instance. This method exists purely to
allow client code of APIs that hide the underlying transport to
eagerly close the transport as a way to signal to the producer
of the stream that the read side is shut down. For example,
when interacting with the standard out pipe of a sub-process.
In other words, it is not an error to not to call close() on
:class:`StreamReader` instance you've been given.

.. versionadded:: next

StreamWriter
============
Expand Down
4 changes: 4 additions & 0 deletions Lib/asyncio/streams.py
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,10 @@ def set_exception(self, exc):
if not waiter.cancelled():
waiter.set_exception(exc)

def close(self):
if self._transport is not None:
self._transport.close()

def _wakeup_waiter(self):
"""Wakeup read*() functions waiting for data or EOF."""
waiter = self._waiter
Expand Down
28 changes: 28 additions & 0 deletions Lib/test/test_asyncio/test_subprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,17 @@
'data = sys.stdin.buffer.read()',
'sys.stdout.buffer.write(data)'))]

# Program generating infinite data
PROGRAM_YES = [
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason to make this a global var? Maybe we can just define it in test?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No reason other than consistency with PROGRAM_CAT and PROGRAM_BLOCKED. I can make it a local variable.

sys.executable, '-c', """\
import sys
while True:
try:
sys.stdout.buffer.write(b"y\\n")
except BrokenPipeError:
break
"""]


def tearDownModule():
asyncio._set_event_loop_policy(None)
Expand Down Expand Up @@ -879,6 +890,23 @@ async def main():

self.loop.run_until_complete(main())

def test_subprocess_break_pipe(self):
# See https://github.com/python/cpython/issues/130925
async def main():
proc = await asyncio.create_subprocess_exec(*PROGRAM_YES,
stdout=asyncio.subprocess.PIPE)
try:
# just make sure the program has executed correctly
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
# just make sure the program has executed correctly

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added that comment so it's clear why those otherwise unnecessary lines of code are there. They aren't conceptually part of the unit test though. I can be more clear.

data = await proc.stdout.readline()
self.assertEqual(data, b"y\n")
finally:
# we are testing that the following method exists and
# has the intended effect of signaling the sub-process to terminate
Comment on lines +903 to +904
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
# we are testing that the following method exists and
# has the intended effect of signaling the sub-process to terminate

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as before, the comment is there to make it explicit what the intent of the test is and the code included in the test.

proc.stdout.close()
await proc.wait()

self.loop.run_until_complete(main())


if sys.platform != 'win32':
# Unix
Expand Down
1 change: 1 addition & 0 deletions Misc/ACKS
Original file line number Diff line number Diff line change
Expand Up @@ -836,6 +836,7 @@ Roberto Hueso Gomez
Jim Hugunin
Greg Humphreys
Chris Hunt
Rian Hunter
Eric Huss
Nehal Hussain
Taihyun Hwang
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
:func:`asyncio.StreamReader.close` now exists so that it's possible to
signal to sub-processes executed via :func:`asyncio.create_subprocess_exec`
that they may cease generating output and exit cleanly.
Comment on lines +1 to +3
Copy link
Member

@sobolevn sobolevn Mar 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
:func:`asyncio.StreamReader.close` now exists so that it's possible to
signal to sub-processes executed via :func:`asyncio.create_subprocess_exec`
that they may cease generating output and exit cleanly.
Add :func:`asyncio.StreamReader.close` method. It can signal to sub-processes executed via :func:`asyncio.create_subprocess_exec`
that they may cease generating output and exit cleanly.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the "so" was a typo? Otherwise I can change this

Loading