Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/python/asyncio_examples/subprocess_communicate.py
1240 views
1
import asyncio
2
3
async def echo(msg):
4
# Run an echo subprocess
5
process = await asyncio.create_subprocess_exec(
6
'cat',
7
# stdin must a pipe to be accessible as a process.stdin
8
stdin=asyncio.subprocess.PIPE,
9
stdout=asyncio.subprocess.PIPE)
10
# Write a message
11
12
print(('Writing {!r}...'.format(msg)))
13
process.stdin.write(msg.encode() + b'\n')
14
15
# Read reply
16
17
data = await process.stdout.readline()
18
reply = data.decode().strip()
19
20
print(("Received {!r}".format(reply)))
21
22
# Stop the subprocess
23
24
process.terminate()
25
code = await process.wait()
26
27
print(("Terminated with code {}".format(code)))
28
29
30
loop = asyncio.get_event_loop()
31
loop.run_until_complete(echo('hello!'))
32
loop.close()
33
34