summaryrefslogtreecommitdiff
path: root/examples/subprocess_stream.py
blob: c33cdc78219dd96808578efbffda0a19d97cbca5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import asyncio

@asyncio.coroutine
def cat(loop):
    transport, protocol = yield from asyncio.subprocess_shell("cat")
    print("pid: %s" % transport.get_pid())
    stdin = protocol.stdin
    stdout = protocol.stdout

    message = "Hello World!"
    print("cat write: %r" % message)
    stdin.write(message.encode('ascii'))
    yield from stdin.drain()

    stdin.close()
    read = yield from stdout.read()
    print("cat read: %r" % read.decode('ascii'))
    transport.close()

@asyncio.coroutine
def ls(loop):
    transport, protocol = yield from asyncio.subprocess_shell("ls", stdin=None)
    while True:
        line = yield from protocol.stdout.readline()
        if not line:
            break
        print("ls>>", line.decode('ascii').rstrip())
    transport.close()

loop = asyncio.get_event_loop()
loop.run_until_complete(cat(loop))
loop.run_until_complete(ls(loop))