Skip to content

Instantly share code, notes, and snippets.

@minrk
Created March 28, 2018 09:32
Show Gist options
  • Save minrk/355368cd135b2e30b05195a1671bc17e to your computer and use it in GitHub Desktop.
Save minrk/355368cd135b2e30b05195a1671bc17e to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "import asyncio\n\nfrom concurrent.futures import ThreadPoolExecutor\nimport textwrap\n\naio_pool = ThreadPoolExecutor(1)\n\ndef init_loop():\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n return loop\n\naio_loop = aio_pool.submit(init_loop).result()\n\nasync def mycoro():\n await asyncio.sleep(1)\n return 5\n\nresult = aio_pool.submit(lambda : aio_loop.run_until_complete(mycoro())).result()\n\nip = get_ipython()\ndef asyncio_magic(line, cell):\n async_cell = \"async def __async_f():\\n%s\" % textwrap.indent(cell, ' ')\n exec(async_cell, ip.user_ns)\n f = ip.user_ns['__async_f']\n \n result = aio_pool.submit(lambda : aio_loop.run_until_complete(f())).result()\n\nip.register_magic_function(asyncio_magic, magic_kind='cell', magic_name='asyncio')\n ",
"execution_count": 1,
"outputs": []
},
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "%%asyncio\nprint('waiting')\nawait asyncio.sleep(1)\nprint('waited')\n",
"execution_count": 2,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "waiting\nwaited\n"
}
]
}
],
"metadata": {
"kernelspec": {
"name": "python3",
"display_name": "Python 3",
"language": "python"
},
"language_info": {
"name": "python",
"version": "3.6.4",
"mimetype": "text/x-python",
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"pygments_lexer": "ipython3",
"nbconvert_exporter": "python",
"file_extension": ".py"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment