def install():
  """Install the context tracking reactor."""

  # Install logging patches.
  originalFormatter = log.textFromEventDict

  def newFormatter(*args, **kw):
    """Augmented log formatter that includes context information."""
    originalResult = originalFormatter(*args, **kw)
    values = AsyncFrame.currentFrame.getLocals()
    if values:
      originalResult += ' %r' % values
    return originalResult

  log.textFromEventDict = newFormatter


  # Patch threads.deferToThread(Pool)
  originalDeferToThreadPool = threads.deferToThreadPool

  def deferToThreadPool(*args, **kw):
    """Patches defer to thread pool to install the context when running the callback."""
    deferred = originalDeferToThreadPool(*args, **kw)
    # pylint: disable=W0212
    deferred._startRunCallbacks = wrapped(deferred._startRunCallbacks, 'Thread')
    return deferred

  threads.deferToThreadPool = deferToThreadPool


  # Overwrite the reactor.
  del sys.modules['twisted.internet.reactor']
  r = FrameTrackingReactor()
  from twisted.internet.main import installReactor
  installReactor(r)
def install(runLoop=None, runner=None):
    """
    Configure the twisted mainloop to be run inside CFRunLoop.

    @param runLoop: the run loop to use.

    @param runner: the function to call in order to actually invoke the main
        loop.  This will default to L{CFRunLoopRun} if not specified.  However,
        this is not an appropriate choice for GUI applications, as you need to
        run NSApplicationMain (or something like it).  For example, to run the
        Twisted mainloop in a PyObjC application, your C{main.py} should look
        something like this::

            from PyObjCTools import AppHelper
            from twisted.internet.cfreactor import install
            install(runner=AppHelper.runEventLoop)
            # initialize your application
            reactor.run()

    @return: The installed reactor.

    @rtype: L{CFReactor}
    """

    reactor = CFReactor(runLoop=runLoop, runner=runner)
    from twisted.internet.main import installReactor
    installReactor(reactor)
    return reactor
def install():
    """Configure the twisted mainloop to be run using the select() reactor.
    """
    reactor = ThreadedSelectReactor()
    from twisted.internet.main import installReactor
    installReactor(reactor)
    return reactor
Beispiel #4
0
def install():
    """
    Configure the twisted mainloop to be run inside the qt mainloop.
    """
    from twisted.internet import main
    reactor = QTReactor()
    main.installReactor(reactor)
Beispiel #5
0
def install():
    """
    Install the kqueue() reactor.
    """
    p = KQueueReactor()
    from twisted.internet.main import installReactor
    installReactor(p)
def install():
    """
    Install the Qt reactor.
    """
    p = QtReactor()
    from twisted.internet.main import installReactor
    installReactor(p)
def install():
    """
    Install the epoll() reactor.
    """
    p = EPollReactor()
    from twisted.internet.main import installReactor
    installReactor(p)
Beispiel #8
0
def install(app=None):
	"""
	Configure the twisted mainloop to be run inside the e2 mainloop.
	"""
	from twisted.internet import main
	reactor = e2reactor()
	main.installReactor(reactor)
	def __init__(self, evManager):
		self.state = ReactorSpinController.STATE_STOPPED
		self.evManager = evManager
		self.evManager.RegisterListener( self )
		self.reactor = SelectReactor()
		installReactor(self.reactor)
		self.loopingCall = LoopingCall(self.FireTick)
Beispiel #10
0
def install():
    """Configure the twisted mainloop to be run inside the wxPython mainloop.
    """
    reactor = WxReactor()
    from twisted.internet.main import installReactor
    installReactor(reactor)
    return reactor
Beispiel #11
0
def portableInstall():
    """Configure the twisted mainloop to be run inside the gtk mainloop.
    """
    reactor = PortableGtkReactor()
    from twisted.internet.main import installReactor
    installReactor(reactor)
    return reactor
Beispiel #12
0
def win32install():
    """
    Install the Qt reactor.
    """
    p = QtEventReactor()
    from twisted.internet.main import installReactor
    installReactor(p)
    return p
Beispiel #13
0
def install(io_loop=None):
    """Install this package as the default Twisted reactor."""
    if not io_loop:
        io_loop = IOLoop.instance()
    reactor = TornadoReactor(io_loop)
    from twisted.internet.main import installReactor
    installReactor(reactor)
    return reactor
Beispiel #14
0
def win32install():
    """
    Install the Qt reactor.
    """
    p = pyqt4eventreactor()
    from twisted.internet.main import installReactor

    installReactor(p)
def install():
    """
    Setup Twisted+Pyglet integration based on the Pyglet event loop.
    """
    reactor = PygletReactor()
    from twisted.internet.main import installReactor
    installReactor(reactor)
    return reactor
Beispiel #16
0
def posixinstall():
    """
    Install the Qt reactor.
    """
    p = pyqt4reactor()
    from twisted.internet.main import installReactor

    installReactor(p)
Beispiel #17
0
def posixinstall():
    """
    Install the Qt reactor.
    """

    from twisted.internet.main import installReactor
    p = QtReactor()
    installReactor(p)
Beispiel #18
0
def install(io_loop=None):
    """Install this package as the default Twisted reactor."""
    if not io_loop:
        io_loop = webalchemy.tornado.ioloop.IOLoop.current()
    reactor = TornadoReactor(io_loop)
    from twisted.internet.main import installReactor
    installReactor(reactor)
    return reactor
Beispiel #19
0
def install():
    """
    Configure the twisted mainloop to be run inside the npyscreen mainloop.
    """
    reactor = NpyscreenReactor()
    from twisted.internet.main import installReactor
    installReactor(reactor)
    return reactor
Beispiel #20
0
def install(runLoop=None):
    """Configure the twisted mainloop to be run inside CFRunLoop.
    """
    reactor = CFReactor(runLoop=runLoop)
    reactor.addSystemEventTrigger('after', 'shutdown', reactor.cleanup)
    from twisted.internet.main import installReactor
    installReactor(reactor)
    return reactor
 def __init__(self):
     self.keepGoing = True
     self.reactor = SelectReactor()
     installReactor(self.reactor)
     connection = self.reactor.connectTCP('localhost', 8000, factory)
     self.reactor.startRunning()
     self.futureCall = None
     self.futureCallTimeout = None
     pygame_test.prepare()
Beispiel #22
0
def install(app=None):
    """Configure the twisted mainloop to be run inside the qt mainloop.
    """
    reactor = QTReactor(app=app)
    reactor.addSystemEventTrigger('after', 'shutdown', reactor.cleanup )
    reactor.simulate()
    from twisted.internet.main import installReactor
    installReactor(reactor)
    return reactor
Beispiel #23
0
 def test_installReactor(self):
     """
     L{installReactor} installs a new reactor if none is present.
     """
     with NoReactor():
         newReactor = object()
         installReactor(newReactor)
         from twisted.internet import reactor
         self.assertIdentical(newReactor, reactor)
Beispiel #24
0
 def test_alreadyInstalled(self):
     """
     If a reactor is already installed, L{installReactor} raises
     L{ReactorAlreadyInstalledError}.
     """
     with NoReactor():
         installReactor(object())
         self.assertRaises(ReactorAlreadyInstalledError, installReactor,
                           object())
Beispiel #25
0
def install(eventloop=None):
    """
    Install a tulip-based reactor.
    """
    if eventloop is None:
        eventloop = get_event_loop()
    reactor = AsyncioSelectorReactor(eventloop)
    from twisted.internet.main import installReactor
    installReactor(reactor)
Beispiel #26
0
def install(useGtk=True):
    """Configure the twisted mainloop to be run inside the gtk mainloop.
    @param useGtk: should glib rather than GTK+ event loop be
    used (this will be slightly faster but does not support GUI).
    """
    reactor = Gtk2Reactor(useGtk)
    from twisted.internet.main import installReactor
    installReactor(reactor)
    return reactor
Beispiel #27
0
def install():
    """
    Configure the twisted mainloop to be run using the kaa reactor.
    """
    reactor = KaaReactor()
    from twisted.internet.main import installReactor
    installReactor(reactor)
    reactor.connect()
    return reactor
def install(eventloop=None):
    """
    Install an asyncio-based reactor.

    @param eventloop: The asyncio eventloop to wrap. If default, the global one
        is selected.
    """
    reactor = AsyncioSelectorReactor(eventloop)
    from twisted.internet.main import installReactor
    installReactor(reactor)
Beispiel #29
0
def install(io_loop=None):
    """
    Install the Tornado reactor.
    """
    if not io_loop:
        io_loop = tornado.ioloop.IOLoop.instance()
    reactor = TornadoReactor(io_loop)
    from twisted.internet.main import installReactor
    installReactor(reactor)
    return reactor
Beispiel #30
0
def install():
    k = KQueueReactor()
    main.installReactor(k)
Beispiel #31
0
    def removeAll(self):
        return get_event_loop().remove_all()

    #######################################################################
    # Functions not needed by pulsar
    _registerAsIOThread = False

    def installWaker(self):
        pass

    def mainLoop(self):
        pass

    def doIteration(self, delay):
        pass

    def spawnProcess(self, *args, **kwargs):
        raise NotImplementedError('Cannot spawn process from Pulsar reactor')

    def _initThreads(self):
        pass

    def _handleSignals(self):
        pass


if installReactor:  # pragma    nocover
    _reactor = PulsarReactor()
    installReactor(_reactor)
    _reactor.run()
Beispiel #32
0
 def install(klass):
     """ Install custom reactor """
     if sys.modules.has_key('twisted.internet.reactor'):
         del sys.modules['twisted.internet.reactor']
     Hellanzb.reactor = HellaReactor()
     installReactor(Hellanzb.reactor)
import scrapy
from scrapy.crawler import CrawlerProcess
from twisted.internet.main import installReactor
from twisted.internet.selectreactor import SelectReactor


class SelectReactorSubclass(SelectReactor):
    pass


reactor = SelectReactorSubclass()
installReactor(reactor)


class NoRequestsSpider(scrapy.Spider):
    name = 'no_request'

    def start_requests(self):
        return []


process = CrawlerProcess(
    settings={
        "TWISTED_REACTOR": "twisted.internet.selectreactor.SelectReactor",
    })

process.crawl(NoRequestsSpider)
process.start()
Beispiel #34
0
 def setup_reactor(self):
     self.reactor = pollreactor.PollReactor()
     installReactor(self.reactor)
def install():
    """Configure the twisted mainloop to be run using geventreactor."""
    reactor = GeventReactor()
    from twisted.internet.main import installReactor
    installReactor(reactor)
# "AGPLv3".  If not, see <http://www.gnu.org/licenses/>.
#

import sys, os
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, SCRIPT_DIR)
sys.path.insert(0, "..")

from twisted.trial import unittest, runner, reporter

from twisted.internet import selectreactor, main
class MyReactor(selectreactor.SelectReactor):
      def runUntilCurrent(self):
            self._cancellations = 20000000
            selectreactor.SelectReactor.runUntilCurrent(self)
main.installReactor(MyReactor())
from twisted.internet import defer, reactor
from twisted.application import internet
from twisted.python import failure
from twisted.python.runtime import seconds
import twisted.internet.base
twisted.internet.base.DelayedCall.debug = True

from twisted.web import client, http

from tests import testmessages
verbose = int(os.environ.get('VERBOSE_T', '-1'))
if verbose < 0: testmessages.silence_all_messages()

from tests import testclock
Beispiel #37
0
def install():
    from twisted.internet.main import installReactor
    reactor = Qt4Reactor()
    installReactor(reactor)
    return reactor
Beispiel #38
0
def install_pausing_reactor():
    class PausingReactor(SelectReactor):
        """A SelectReactor that can be paused and resumed."""
        def __init__(self):
            SelectReactor.__init__(self)
            self.paused = False
            self._return_value = None
            self._release_requested = False
            self._mainLoopGen = None

            # Older versions of twisted do not have the _started attribute, make it a synonym for running in that case
            if not hasattr(self, '_started'):
                PausingReactor._started = property(lambda self: self.running)

        def _mainLoopGenerator(self):
            """Generator that acts as mainLoop, but yields when requested."""
            while self._started:
                try:
                    while self._started:
                        if self._release_requested:
                            self._release_requested = False
                            self.paused = True
                            yield self._return_value
                            self.paused = False
                        self.iterate()
                except KeyboardInterrupt:
                    # Keyboard interrupt pauses the reactor
                    self.pause()
                except GeneratorExit:
                    # GeneratorExit means stop the generator; Do it cleanly by stopping the whole reactor.
                    log.debug('Got GeneratorExit, stopping reactor.',
                              exc_info=True)
                    self.paused = False
                    self.stop()
                except:
                    twisted_log.msg("Unexpected error in main loop.")
                    twisted_log.err()
                else:
                    twisted_log.msg('Main loop terminated.')

        def run(self, installSignalHandlers=False):
            """Starts or resumes the reactor."""
            if not self._started:
                self.startRunning(installSignalHandlers)
                self._mainLoopGen = self._mainLoopGenerator()
            try:
                return next(self._mainLoopGen)
            except StopIteration:
                pass

        def pause(self, return_value=None):
            """Causes reactor to pause after this iteration.
            If :return_value: is specified, it will be returned by the reactor.run call."""
            self._return_value = return_value
            self._release_requested = True

        def stop(self):
            """Stops the reactor."""
            SelectReactor.stop(self)
            # If this was called while the reactor was paused we have to resume in order for it to complete
            if self.paused:
                self.run()

            # These need to be re-registered so that the PausingReactor can be safely restarted after a stop
            self.addSystemEventTrigger('during', 'shutdown', self.crash)
            self.addSystemEventTrigger('during', 'shutdown',
                                       self.disconnectAll)

    # Configure twisted to use the PausingReactor.
    installReactor(PausingReactor())

    @event('manager.shutdown')
    def stop_reactor(manager):
        """Shut down the twisted reactor after all tasks have run."""
        if not reactor._stopped:
            log.debug('Stopping twisted reactor.')
            reactor.stop()
Beispiel #39
0
def install():
    """Configure the twisted mainloop to be run using the select() reactor."""
    reactor = SelectReactor()
    from twisted.internet.main import installReactor

    installReactor(reactor)
Beispiel #40
0
def install():
    """Install the poll() reactor."""
    p = PollReactor()
    from twisted.internet.main import installReactor
    installReactor(p)
Beispiel #41
0
def install():
    """Install the Syncless reactor."""
    # As a side effect, this calls `from syncless import coio', which
    # creates and starts the coio.main_loop_tasklet, which calls
    # event_loop() indefinitely.
    installReactor(SynclessReactor())
Beispiel #42
0
def install():
    """Use the VIFF reactor."""
    reactor = ViffReactor()
    from twisted.internet.main import installReactor
    installReactor(reactor)
Beispiel #43
0
def posixinstall():
    """Install the Qt reactor."""
    from twisted.internet.main import installReactor
    p = QtReactor()
    installReactor(p)
Beispiel #44
0
def win32install():
    """Install the Qt reactor."""
    from twisted.internet.main import installReactor
    p = QtEventReactor()
    installReactor(p)
Beispiel #45
0
            self._return_value = return_value
            self._release_requested = True

        def stop(self):
            """Stops the reactor."""
            SelectReactor.stop(self)
            # If this was called while the reactor was paused we have to resume in order for it to complete
            if self.paused:
                self.run()

            # These need to be re-registered so that the PausingReactor can be safely restarted after a stop
            self.addSystemEventTrigger('during', 'shutdown', self.crash)
            self.addSystemEventTrigger('during', 'shutdown', self.disconnectAll)

    # Configure twisted to use the PausingReactor.
    installReactor(PausingReactor())

except ImportError:
    # If twisted is not found, errors will be shown later
    pass


# Define a base class with some methods that are used for all deluge versions
class DelugePlugin(object):
    """Base class for deluge plugins, contains settings and methods for connecting to a deluge daemon."""

    def prepare_connection_info(self, config):
        config.setdefault('host', 'localhost')
        config.setdefault('port', 58846)
        if 'user' in config or 'pass' in config:
            warnings.warn('deluge `user` and `pass` options have been renamed `username` and `password`',
def install():
    """Install the poll() reactor."""

    p = PollReactor()
    main.installReactor(p)
Beispiel #47
0
def install():
    threadable.init(1)
    r = Win32Reactor()
    import main
    main.installReactor(r)
Beispiel #48
0
def install():
    from twisted.python import threadable
    p = Proactor()
    threadable.init()
    main.installReactor(p)
Beispiel #49
0
def install():
    r = IOCPReactor()
    main.installReactor(r)
Beispiel #50
0
def install():
    reactor = PygletReactor()
    from twisted.internet.main import installReactor
    installReactor(reactor)
    return reactor
Beispiel #51
-1
def install():
    """
    Configure the twisted mainloop to be run inside the glib mainloop.
    """
    reactor = Glib2Reactor()
    from twisted.internet.main import installReactor
    installReactor(reactor)