Skip to content

Instantly share code, notes, and snippets.

@legnaleurc
Last active November 17, 2018 21:27
Show Gist options
  • Save legnaleurc/d541c238e22cd6b675c8 to your computer and use it in GitHub Desktop.
Save legnaleurc/d541c238e22cd6b675c8 to your computer and use it in GitHub Desktop.
Tornado v.s. asyncio (Python 3.5+)
#! /usr/bin/env python3
import asyncio
import contextlib
async def ping(ip):
p = await asyncio.create_subprocess_exec('ping', '-c', '4', ip, stdout=asyncio.subprocess.PIPE)
async for line in p.stdout:
print(line)
await p.wait()
async def main():
await asyncio.wait([
ping('8.8.8.8'),
ping('8.8.4.4'),
])
if __name__ == '__main__':
with contextlib.closing(asyncio.get_event_loop()) as main_loop:
main_loop.run_until_complete(main())
#! /usr/bin/env python3
from tornado import gen, ioloop, process
async def ping(ip):
p = process.Subprocess(['ping', '-c', '4', ip], stdout=process.Subprocess.STREAM)
await p.stdout.read_until_close(streaming_callback=print)
await p.wait_for_exit()
async def main():
await gen.multi([
ping('8.8.8.8'),
ping('8.8.4.4'),
])
if __name__ == '__main__':
main_loop = ioloop.IOLoop.instance()
main_loop.run_sync(main)
@legnaleurc
Copy link
Author

I suspect that's a Windows specific problem, e.g. missing proper event loop implementation.
Sadly I don't have a Windows machine for Python developing, so I can't help. :(

@lexdene
Copy link

lexdene commented Oct 31, 2016

Your example is so simple and clear that it helps me understand async programming in Python.
Thank you so much.

@papersaltserver
Copy link

For working Windows asyncio you need to change EventLoop:
add:
loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(loop)

also "-c 4" for windows works not the same way as in Linux, so you just need to remove this arguments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment