Last active
August 28, 2019 15:00
-
-
Save studiotomi/8a2be58cd59eb6768964 to your computer and use it in GitHub Desktop.
Asyncrounous Anything in python 3
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 threading | |
from queue import Queue | |
class AsyncThread(threading.Thread): | |
""" | |
Based off of ssynchronous downloading script pull from stackoverflow | |
http://stackoverflow.com/questions/18883964/asynchronous-file-downloads-in-python | |
""" | |
def __init__(self, queue, func): | |
super(AsyncThread, self).__init__() | |
self.queue = queue | |
self.func = func | |
self.daemon = True | |
def run(self): | |
while True: | |
item = self.queue.get() | |
try: | |
self.func(item) | |
except Exception as e: | |
print(" Error: %s" % e) | |
self.queue.task_done() | |
def run_async(items, func, numthreads=4): | |
""" | |
Items is a list of tuples: | |
(url, desitnation folder) | |
""" | |
queue = Queue() | |
for item in items: | |
queue.put(item) | |
for i in range(numthreads): | |
t = AsyncThread(queue, func) | |
t.start() | |
queue.join() | |
items = list(glob("*")) | |
run_async(items, some_func) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment