Last active
December 27, 2016 17:57
-
-
Save onlurking/6ca6d213ab98a8c4fa70728bdd39e5c8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
from urllib.request import urlopen | |
async def produce_lines(filename, delay): | |
try: | |
with open(filename, 'r') as file: | |
for line in file: | |
yield line.rstrip('\n') | |
await asyncio.sleep(delay) | |
except FileNotFoundError: | |
with open("poe1.txt", 'w', encoding='utf8') as file: | |
file.write( | |
(urlopen("http://www.gutenberg.org/dirs/2/1/4/2147/2147-8.txt") | |
.read() | |
.decode("iso8859"))) | |
print("Hi, I've downloaded the The Works of Edgar Allan Poe (Volume 1) for you.\nPlease, re-run this program, shall you..?") | |
async def print_lines(filename, delay): | |
async for line in produce_lines(filename, delay): | |
print(f'[{filename}]', line) | |
def main(): | |
loop = asyncio.get_event_loop() | |
tasks = [asyncio.Task(print_lines("poe1.txt", 0.5)), | |
asyncio.Task(print_lines("poe2.txt", 0.3)), | |
asyncio.Task(print_lines("poe3.txt", 0.6)), | |
asyncio.Task(print_lines("poe4.txt", 0.5)), | |
asyncio.Task(print_lines("poe5.txt", 0.2))] | |
loop.run_until_complete(asyncio.gather(*tasks)) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You will need download the Works of Edgar Allan Poe for this one: