Skip to content

Instantly share code, notes, and snippets.

@athoune
Created October 10, 2016 12:16
Show Gist options
  • Save athoune/0736f73368fac38f066ac7cbf82ff5eb to your computer and use it in GitHub Desktop.
Save athoune/0736f73368fac38f066ac7cbf82ff5eb to your computer and use it in GitHub Desktop.
async ping for python 3
#!/usr/bin/env python3
import asyncio
@asyncio.coroutine
def ping(loop, target, dump=False):
create = asyncio.create_subprocess_exec('ping', '-c', '10', target,
stdout=asyncio.subprocess.PIPE)
proc = yield from create
lines = []
while True:
line = yield from proc.stdout.readline()
if line == b'':
break
l = line.decode('utf8').rstrip()
if dump:
print(l)
lines.append(l)
transmited, received = [int(a.split(' ')[0]) for a
in lines[-2].split(', ')[:2]]
stats, unit = lines[-1].split(' = ')[-1].split(' ')
min_, avg, max_, stddev = [float(a) for a in stats.split('/')]
return transmited, received, unit, min_, avg, max_, stddev
if __name__ == '__main__':
loop = asyncio.get_event_loop()
ping = loop.run_until_complete(ping(loop, 'free.fr'))
print(ping)
loop.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment