{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Thread pool executor\n\n``Asyncio``/``concurrent`` heavily changed from python ``3.4`` to ``3.7``, better read the docs\nand do some tutorials. Asyncio is preferred over plain concurrent module. \n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import concurrent.futures\nimport urllib.request\n\nURLS = [\n \"http://www.foxnews.com/\",\n \"http://www.cnn.com/\",\n \"http://europe.wsj.com/\",\n \"http://www.bbc.co.uk/\",\n \"http://some-made-up-domain.com/\",\n]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Retrieve a single page and report the url and contents\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def load_url(url, timeout):\n with urllib.request.urlopen(url, timeout=timeout) as conn:\n return conn.read()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can use a with statement to ensure threads are cleaned up promptly\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:\n # Start the load operations and mark each future with its URL\n future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}\n for future in concurrent.futures.as_completed(future_to_url):\n url = future_to_url[future]\n try:\n data = future.result()\n except Exception as exc:\n print(\"%r generated an exception: %s\" % (url, exc))\n else:\n print(\"%r page is %d bytes\" % (url, len(data)))" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.10" } }, "nbformat": 4, "nbformat_minor": 0 }