Files
deb-python-trollius/examples/subprocess_attach_read_pipe.py
Victor Stinner 684f3be000 Python issue #23208: Add BaseEventLoop._current_handle
In debug mode, BaseEventLoop._run_once() now sets the
BaseEventLoop._current_handle attribute to the handle currently executed.
In release mode or when no handle is executed, the attribute is None.

BaseEventLoop.default_exception_handler() displays the traceback of the current
handle if available.
2015-01-26 10:52:45 +01:00

34 lines
806 B
Python

#!/usr/bin/env python3
"""Example showing how to attach a read pipe to a subprocess."""
import asyncio
import os, sys
code = """
import os, sys
fd = int(sys.argv[1])
os.write(fd, b'data')
os.close(fd)
"""
loop = asyncio.get_event_loop()
@asyncio.coroutine
def task():
rfd, wfd = os.pipe()
args = [sys.executable, '-c', code, str(wfd)]
pipe = open(rfd, 'rb', 0)
reader = asyncio.StreamReader(loop=loop)
protocol = asyncio.StreamReaderProtocol(reader, loop=loop)
transport, _ = yield from loop.connect_read_pipe(lambda: protocol, pipe)
proc = yield from asyncio.create_subprocess_exec(*args, pass_fds={wfd})
yield from proc.wait()
os.close(wfd)
data = yield from reader.read()
print("read = %r" % data.decode())
loop.run_until_complete(task())
loop.close()