-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathasyncio_subprocess_coroutine_write.py
More file actions
48 lines (38 loc) · 1.06 KB
/
asyncio_subprocess_coroutine_write.py
File metadata and controls
48 lines (38 loc) · 1.06 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import asyncio
import asyncio.subprocess
async def to_upper(input):
print("in to_upper")
create = asyncio.create_subprocess_exec(
"tr",
"[:lower:]",
"[:upper:]",
stdout=asyncio.subprocess.PIPE,
stdin=asyncio.subprocess.PIPE,
)
print("launching process")
proc = await create
print("pid: {}".format(proc.pid))
print("communicating with process")
stdout, stderr = await proc.communicate(input.encode())
await proc.wait()
return_code = proc.returncode
print("return code {}".format(return_code))
if not return_code:
results = bytes(stdout).decode()
else:
results = ""
return return_code, results
MESSAGE = """
This message will be converted
to all caps.
"""
event_loop = asyncio.get_event_loop()
try:
return_code, results = event_loop.run_until_complete(to_upper(MESSAGE))
finally:
event_loop.close()
if return_code:
print("error exit {}".format(return_code))
else:
print("Original: {!r}".format(MESSAGE))
print("Changed: {!r}".format(results))