当前位置: 首页>>代码示例>>Python>>正文


Python threadpool.ThreadPool类代码示例

本文整理汇总了Python中gevent.threadpool.ThreadPool的典型用法代码示例。如果您正苦于以下问题:Python ThreadPool类的具体用法?Python ThreadPool怎么用?Python ThreadPool使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了ThreadPool类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: ELExpression

class ELExpression():
    def __init__(self):
        self.result = []
        self.pool = ThreadPool(10)
        self.q = []
        self.payload = '{1000-121}'
        self.match = '879'

    def putinqueue(self, info):
        try:

            url = info[0]
            data = info[1]
            current = data if data else url
            for k in re.finditer(r'\=(?P<value>.*?)(?:$|&)', current):
                value = k.group('value')
                payload = current.replace(value, self.payload)
                if data:
                    self.q.append((url, payload))
                else:
                    self.q.append((payload, data))
        except:
            traceback.print_exc()

    def Fuzz(self, info):
        try:
            url = info[0]
            data = info[1]
            if data:
                try:
                    r = requests.post(url, data=data, timeout=10, verify=False)
                    content = r.content
                except:
                    content = ''
            else:
                try:
                    print "Req ::" + url
                    r = requests.get(url, timeout=10, verify=False)
                    content = r.content
                except:
                    content = ''
                if self.match in content:
                    msg = 'find vulnerable url'
                    logging.info(msg)
                    self.result.append(info)
        except:
            traceback.print_exc()

    def Scan(self, info):
        try:
            if isinstance(info, tuple):
                self.putinqueue(info)
            else:
                with open(info) as f:
                    ud = json.loads(f.read())
                for i in ud:
                    self.putinqueue(i)
            self.pool.map(self.Fuzz, self.q)
        except:
            traceback.print_exc()
开发者ID:N2dos,项目名称:vulscans,代码行数:60,代码来源:ELExpression.py

示例2: _run

 def _run(self):
     try:
         args = self.orbname, self.select, self.reject
         # TODO Review this queue size
         # TODO Review reasoning behind using OrbreapThr vs. normal ORB API
         # I think it had something to do with orb.reap() blocking forever
         # on comms failures; maybe we could create our own orbreapthr
         # implementation?
         with OrbreapThr(*args, timeout=1, queuesize=orbreapthr_queuesize) as orbreapthr:
             log.info("Connected to ORB %s %s %s" % (self.orbname, self.select,
                                                     self.reject))
             threadpool = ThreadPool(maxsize=1)
             try:
                 while True:
                     try:
                         success, value = threadpool.spawn(
                                 wrap_errors, (Exception,), orbreapthr.get, [], {}).get()
                         timestamp = datetime.utcnow()
                         if not success:
                             raise value
                     except (Timeout, NoData), e:
                         log.debug("orbreapthr.get exception %r" % type(e))
                         pass
                     else:
                         if value is None:
                             raise Exception('Nothing to publish')
                         self._publish(value, timestamp)
             finally:
                 # This blocks until all threads in the pool return. That's
                 # critical; if the orbreapthr dies before the get thread,
                 # segfaults ensue.
                 threadpool.kill()
     except Exception, e:
         log.error("OrbPktSrc terminating due to exception", exc_info=True)
         raise
开发者ID:n1ywb,项目名称:wavefront,代码行数:35,代码来源:orbpktsrc.py

示例3: ThreadPoolExecutor

class ThreadPoolExecutor(concurrent.futures.ThreadPoolExecutor):
  """
  A version of :class:`concurrent.futures.ThreadPoolExecutor` that
  always uses native threads, even when threading is monkey-patched.

  TODO: Gevent has also implemented [ThreadPoolExecutor](https://github.com/gevent/gevent/blob/master/src/gevent/threadpool.py#L454)
   to be released in next version 1.2.0. We should move to that implementation when it is released.
  """

  def __init__(self, max_workers):
    super(ThreadPoolExecutor, self).__init__(max_workers)
    self._threadpool = ThreadPool(max_workers)

  def submit(self, fn, *args, **kwargs):
    future = super(ThreadPoolExecutor, self).submit(fn, *args, **kwargs)
    with self._shutdown_lock:
      work_item = self._work_queue.get()
      assert work_item.fn is fn

    self._threadpool.spawn(work_item.run)
    return future

  def shutdown(self, wait=True):
    super(ThreadPoolExecutor, self).shutdown(wait)
    self._threadpool.kill()

  kill = shutdown  # greentest compat

  def _adjust_thread_count(self):
    # Does nothing. We don't want to spawn any "threads",
    # let the threadpool handle that.
    pass
开发者ID:bastova,项目名称:Grpc-gevent-monkey-thread,代码行数:32,代码来源:greeter_client_with_patched_threadpoolexecutor.py

示例4: run_proxy_parse

    def run_proxy_parse(self, url, proxy_type):
        try:
            for i in range(3):
                #这里对url进行重新组装
                url = url[0:-1] + str(i+1)
                resp = requests.get(url, timeout=5)
                response = etree.HTML(resp.content.decode('utf-8'))
                #解析代理IP,获取代理ip列表
                proxy_ip_list = []
                for item in response.xpath('//tr[contains(@style,"font-size")]'):
                    ip = item.xpath('./td[1]/text()')[0].strip()
                    port = item.xpath('./td[2]/text()')[0].strip()
                    proto = item.xpath('./td[4]/text()')[0].strip()
                    if proto.lower() == 'https':
                        continue
                    proxy_ip = proto.lower() + '://' + ip + ':' + port
                    if proxy_ip not in proxy_ip_list:
                        proxy_ip_list.append(proxy_ip)

                #对每个IP进行测试,留下可用的代理ip
                pool = ThreadPool(len(proxy_ip_list))
                for pip in proxy_ip_list:
                    pool.spawn(self.test_single_proxy, pip, self.test_urls[proxy_type.lower()])
                pool.join()
            
        except Exception, e:
            pass
开发者ID:liudhzhyym,项目名称:mars,代码行数:27,代码来源:httpMiddlewares.py

示例5: Worker

class Worker(object):
    def __init__(self, url):
        self.url = url
        self.headers = {'content-type': 'application/json'}
        self.id = 0
        self.post = functools.partial(requests.post, self.url, headers=self.headers)
        self.pool = ThreadPool(100)

    def _call(self, method, *args):
        payload = dict(method=method, params=args, jsonrpc="2.0", id=self.id)
        self.id += 1
        response = self.post(json.dumps(payload)).json()
        return response

    def _async_call(self, method, *args):
        payload = dict(method=method, params=args, jsonrpc="2.0", id=self.id)
        self.id += 1

        def _delayed_call(pl):
            return self.post(json.dumps(pl)).json()

        return Future(self.pool.spawn(_delayed_call, payload))

    def tell(self, method, *args):
        self._async_call(method, *args)

    def ask(self, method, *args):
        return self._async_call(method, *args)

    def join(self):
        self.pool.join()
开发者ID:rex8312,项目名称:JsonRPCExample,代码行数:31,代码来源:client.py

示例6: _run

 def _run(self):
     """Main loop; reap and process pkts"""
     try:
         args = self.orbname, self.select, self.reject
         print repr(self.orbname)
         print repr(args)
         with OrbreapThr(*args, timeout=1, queuesize=8, after=self.tafter) as orbreapthr:
             log.info("Connected to ORB %s %s %s" % (self.orbname, self.select,
                                                     self.reject))
             self.timeoff = self.timeon = datetime.utcnow()
             spawn(self._status_printer).link_exception(self._janitor)
             threadpool = ThreadPool(maxsize=1)
             try:
                 while True:
                     try:
                         success, value = threadpool.spawn(
                                 wrap_errors, (Exception,), orbreapthr.get, [], {}).get()
                         timestamp = datetime.utcnow()
                         if not success:
                             raise value
                     except (Timeout, NoData), e:
                         log.debug("orbreapthr.get exception %r" % type(e))
                         pass
                     else:
                         if value is None:
                             raise Exception('Nothing to publish')
                         self._process(value, timestamp)
             finally:
                 # This blocks until all threads in the pool return. That's
                 # critical; if the orbreapthr dies before the get thread,
                 # segfaults ensue.
                 threadpool.kill()
     except Exception, e:
         log.error("OrbPktSrc terminating due to exception", exc_info=True)
         raise
开发者ID:n1ywb,项目名称:wavefront,代码行数:35,代码来源:controller.py

示例7: targets

 def targets(self, activity):
     activities = self.get_contacts_by_activity[activity['id']]
     contacts = [int(c) for c in activities[TARGETS]]
     pool = ThreadPool(THREADS)
     contacts = [pool.spawn(self.get_contact, c) for c in contacts]
     gevent.wait()
     contacts = [c.get()['sort_name'] for c in contacts]
     return ', '.join(contacts)
开发者ID:collective,项目名称:collective.civicrm,代码行数:8,代码来源:activities.py

示例8: easy_parallelize_gevent

def easy_parallelize_gevent(f, sequence):
    if not "gevent_pool" in PARALLEL_STRUCTURES:
        from gevent.threadpool import ThreadPool
        pool = ThreadPool(30000)
        PARALLEL_STRUCTURES["gevent_pool"] = pool
    pool = PARALLEL_STRUCTURES["gevent_pool"]
    result = pool.map(f, sequence)
    return result
开发者ID:Marie-Donnie,项目名称:rome,代码行数:8,代码来源:driver.py

示例9: spawn_dashboard

 def spawn_dashboard(self, job, port):
     print 'Spawning dashboard...'
     sp_dashboard = create_fetch_dashboard(job)
     tpool = ThreadPool(2)
     tpool.spawn(sp_dashboard.serve,
                 use_reloader=False,
                 static_prefix='static',
                 port=port,
                 static_path=dashboard._STATIC_PATH)
开发者ID:MarkTraceur,项目名称:womp,代码行数:9,代码来源:fetch.py

示例10: admin_init

    def admin_init(self):
        if self.coll_dir:
            self.load_coll_dir()

        if self.inputs:
            if self.load_cache():
                return

            pool = ThreadPool(maxsize=1)
            pool.spawn(self.safe_auto_load_warcs)
开发者ID:webrecorder,项目名称:webrecorder,代码行数:10,代码来源:webrecorder_player.py

示例11: TestJoinEmpty

class TestJoinEmpty(TestCase):
    switch_expected = False

    def test(self):
        self.pool = ThreadPool(1)
        self.pool.join()

    def cleanup(self):
        # needed here because currently Greenlet.kill() switches out even if greenlet not started yet
        # XXX fix Greenlet.kill
        pass
开发者ID:HVF,项目名称:gevent,代码行数:11,代码来源:test__threadpool.py

示例12: _get_messages

 def _get_messages(self):
     # Emulate batch messages by polling rabbitmq server multiple times
     pool = ThreadPool(settings.POLLER_CONFIG["batchsize"])
     for i in range(settings.POLLER_CONFIG["batchsize"]):
         if settings.QUEUE_TYPE in ["SQS", "sqs"]:
             pool.spawn(self._get_sqs_messages)
         elif settings.QUEUE_TYPE in ["RABBITMQ", "rabbitmq"]:
             pool.spawn(self._get_rabbitmq_messages, i)
         else:
             raise ValueError(
                 'Incorrect value "%s" for QUEUE_TYPE in %s' % (settings.QUEUE_TYPE, settings.SETTINGS_MODULE)
             )
开发者ID:remotesyssupport,项目名称:cito_engine,代码行数:12,代码来源:event_poller.py

示例13: vote

 def vote(self):
     self._voted = False
     if self.sesskey is None or self.choice_id is None:
         self.get_info()
     print("[+] Start threadpool")
     pool = ThreadPool(10)
     for _ in range(11):
         pool.spawn(self._vote, _)
     gevent.wait()
     if self._voted:
         self.vote = True
         print("[+] Vote Success", time.ctime())
开发者ID:kawewutchu,项目名称:Syllabus259191,代码行数:12,代码来源:Syllabus.py

示例14: fetch_controller

def fetch_controller(listname):
    port = find_port()
    if port:
        tpool = ThreadPool(2)
        tpool.spawn(start_fetch, listname, port)
        ret = {'port': port,
               'name': listname,
               'url': 'http://localhost:' + str(port),
               'status': 'running'}
    else:
        ret = {'port': port,
               'name': listname,
               'url': '',
               'status': 'occupied'}
    return ret
开发者ID:MarkTraceur,项目名称:womp,代码行数:15,代码来源:server.py

示例15: __init__

 def __init__(self):
     self.pool = ThreadPool(10)
     self.result = []
     self.port = "5984"
     self.q = []
     self.randomstrs = ['a', 'k', 'b', 'v', 'd', 'f', 'e', 'g']
     self.path = '_utils/index.html'
开发者ID:N2dos,项目名称:vulscans,代码行数:7,代码来源:CouchDb.py


注:本文中的gevent.threadpool.ThreadPool类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。