在单个程序中多次启动扭曲反应堆? [英] Twisted reactor starting multiple times in a single program?

查看:31
本文介绍了在单个程序中多次启动扭曲反应堆?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在同一个程序中多次启动反应器?假设您想将扭曲的功能封装在一个方法中,用于 API 目的.

Is it possible to start the reactor more than once in the same program? Suppose you wanted to encapsulate twisted functionality inside a method, for API purposes.

例如,mymodule.py 看起来像这样:

For example, mymodule.py looks like this:

  1 from twisted.web.client import getPage
  2 from twisted.internet import reactor
  3 
  4 def _result(r):
  5     print r
  6     reactor.stop()
  7 
  8 def _error(e):
  9     print e
 10     reactor.stop()
 11 
 12 def getGoogle():
 13     d = getPage('http://www.google.com')
 14     d.addCallbacks(_result, _error)
 15     reactor.run()
 16 
 17 def getYahoo():
 18     d = getPage('http://www.yahoo.com')
 19     d.addCallbacks(_result, _error)
 20     reactor.run()
 21 

main.py 看起来像这样:

main.py looks like this:

  1 import mymodule
  2 
  3 getGoogle()
  4 getYahoo()

推荐答案

这是组织代码的另一种方式,利用 Twisted 的单线程特性:将所有要处理的 url 排队,启动反应器,然后当每个请求完成时递减一个计数器.当计数器达到零时,停止将返回结果的反应器:

Here's another way to organize your code, exploiting the single-threaded nature of Twisted: queue up all the urls you want to process, kick off the reactor, and decrement a counter when each request completes. When the counter reaches zero, stop the reactor which will return the results:

from twisted.web.client import getPage
from twisted.internet import reactor

class Getter(object):

    def __init__(self):
        self._sequence = 0
        self._results = []
        self._errors = []

    def add(self, url):
        d = getPage(url)
        d.addCallbacks(self._on_success, self._on_error)
        d.addCallback(self._on_finish)
        self._sequence += 1

    def _on_finish(self, *narg):
        self._sequence -= 1
        if not self._sequence:
            reactor.stop()

    _on_success = lambda self, *res: self._results.append(res)
    _on_error = lambda self, *err: self._errors.append(err)

    def run(self):
        reactor.run()
        return self._results, self._errors

g = Getter()
for url in ('http://www.google.com', 'http://www.yahoo.com', 'idontexist'):
    g.add(url)
results, errors = g.run()
print results
print errors

这篇关于在单个程序中多次启动扭曲反应堆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆