| 9 | |
| 10 | |
| 11 | class BaseThread(object): |
| 12 | def __init__(self, targets, concurrency=6): |
| 13 | self.concurrency = concurrency |
| 14 | self.semaphore = threading.Semaphore(concurrency) |
| 15 | self.targets = targets |
| 16 | |
| 17 | def work(self, site): |
| 18 | raise NotImplementedError() |
| 19 | |
| 20 | def _work(self, url): |
| 21 | try: |
| 22 | self.work(url) |
| 23 | except requests.exceptions.RequestException as e: |
| 24 | pass |
| 25 | |
| 26 | except etree.Error as e: |
| 27 | pass |
| 28 | |
| 29 | except Exception as e: |
| 30 | logger.warning("error on {}".format(url)) |
| 31 | logger.exception(e) |
| 32 | |
| 33 | except BaseException as e: |
| 34 | logger.warning("BaseException on {}".format(url)) |
| 35 | raise e |
| 36 | finally: |
| 37 | self.semaphore.release() |
| 38 | |
| 39 | def _run(self): |
| 40 | deque = collections.deque(maxlen=5000) |
| 41 | cnt = 0 |
| 42 | |
| 43 | for target in self.targets: |
| 44 | if isinstance(target, str): |
| 45 | target = target.strip() |
| 46 | |
| 47 | cnt += 1 |
| 48 | logger.debug("[{}/{}] work on {}".format(cnt, len(self.targets), target)) |
| 49 | |
| 50 | if not target: |
| 51 | continue |
| 52 | |
| 53 | self.semaphore.acquire() |
| 54 | t1 = threading.Thread(target=self._work, args=(target,)) |
| 55 | # 可以快速结束程序 |
| 56 | t1.setDaemon(True) |
| 57 | t1.start() |
| 58 | |
| 59 | deque.append(t1) |
| 60 | |
| 61 | for t in list(deque): |
| 62 | while t.is_alive(): |
| 63 | time.sleep(0.2) |
| 64 | |
| 65 | |
| 66 | class ThreadMap(BaseThread): |
nothing calls this directly
no outgoing calls
no test coverage detected