-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathasyncio_subprocess_protocol.py
More file actions
82 lines (65 loc) · 2.09 KB
/
asyncio_subprocess_protocol.py
File metadata and controls
82 lines (65 loc) · 2.09 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import asyncio
import functools
async def run_df(loop):
print("in run_df")
cmd_done = asyncio.Future(loop=loop)
factory = functools.partial(DFProtocol, cmd_done)
proc = loop.subprocess_exec(
factory,
"df",
"-hl",
stdin=None,
stderr=None,
)
try:
print("launching process")
transport, protocol = await proc
print("waiting for process to complete")
await cmd_done
finally:
transport.close()
return cmd_done.result()
class DFProtocol(asyncio.SubprocessProtocol):
FD_NAMES = ["stdin", "stdout", "stderr"]
def __init__(self, done_future):
self.done = done_future
self.buffer = bytearray()
self.transport = None
super().__init__()
def connection_made(self, transport):
print("process started {}".format(transport.get_pid()))
self.transport = transport
def pipe_data_received(self, fd, data):
print("read {} bytes from {}".format(len(data), self.FD_NAMES[fd]))
if fd == 1:
self.buffer.extend(data)
def process_exited(self):
print("process exited")
return_code = self.transport.get_returncode()
print("return code {}".format(return_code))
if return_code == 0:
cmd_output = bytes(self.buffer).decode()
results = self._parse_results(cmd_output)
else:
results = []
self.done.set_result((return_code, results))
def _parse_results(self, output):
print("parsing results")
if not output:
return []
lines = output.splitlines()
headers = lines[0].split()
devices = lines[1:]
results = [dict(zip(headers, line.split())) for line in devices]
return results
event_loop = asyncio.get_event_loop()
try:
return_code, results = event_loop.run_until_complete(run_df(event_loop))
finally:
event_loop.close()
if return_code:
print("error exit {}".format(return_code))
else:
print("\nFree space:")
for r in results:
print("{Mounted:25}: {Avail}".format(**r))