-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathasyncio_subprocess_coroutine.py
More file actions
61 lines (46 loc) · 1.41 KB
/
asyncio_subprocess_coroutine.py
File metadata and controls
61 lines (46 loc) · 1.41 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
import asyncio
import asyncio.subprocess
def _parse_results(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
async def run_df():
print("in run_df")
buffer = bytearray()
create = asyncio.create_subprocess_exec("df", "-hl", stdout=asyncio.subprocess.PIPE)
print("launching process")
proc = await create
print("process started {}".format(proc.pid))
while True:
line = await proc.stdout.readline()
print("read {!r}".format(line))
if not line:
print("no more output from command")
break
buffer.extend(line)
print("waiting for process to complete")
await proc.wait()
return_code = proc.returncode
print("return code {}".format(return_code))
if return_code == 0:
cmd_output = bytes(buffer).decode()
results = _parse_results(cmd_output)
else:
results = []
return return_code, results
event_loop = asyncio.get_event_loop()
try:
return_code, results = event_loop.run_until_complete(run_df())
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))