| Index: examples/tty.py |
| =================================================================== |
| new file mode 100644 |
| --- /dev/null |
| +++ b/examples/tty.py |
| @@ -0,0 +1,33 @@ |
| +""" |
| +Copy stdin into stdout, line by line. |
| +""" |
| + |
| +import asyncio |
| +import sys |
| +from asyncio import streams |
| + |
| +class StdoutProtocol(streams.FlowControlMixin, |
| + asyncio.Protocol): |
| + pass |
| + |
| +@asyncio.coroutine |
| +def copy_stdin_to_stdout(limit): |
| + reader = asyncio.StreamReader(limit=limit) |
| + reader_protocol = asyncio.StreamReaderProtocol(reader) |
| + yield from loop.connect_read_pipe(lambda: reader_protocol, |
| + sys.stdin) |
| + transport, protocol = yield from loop.connect_write_pipe(StdoutProtocol, |
| + sys.stdout) |
| + writer = streams.StreamWriter(transport, protocol, reader, loop) |
| + while True: |
| + line = yield from reader.readline() |
| + if not line: |
| + break |
| + writer.write(line) |
| + yield from writer.drain() |
| + |
| +# readline() fails with ValueError('Line is too long') if a longer line is |
| +# received |
| +max_line_len = 4096 |
| +loop = asyncio.get_event_loop() |
| +loop.run_until_complete(copy_stdin_to_stdout(max_line_len)) |