Python twisted.internet.reactor.run() Examples

The following are 30 code examples of twisted.internet.reactor.run(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twisted.internet.reactor , or try the search function .
Example #1
Source File: server.py    From worker with GNU General Public License v3.0 7 votes vote down vote up
def run():

    config.read()
    logs.api()

    top_service = service.MultiService()

    db = Db()
    datalib.db = db
    db.setServiceParent(top_service)

    http_service = internet.TCPServer(config.HTTP_PORT, Site(db), interface=config.HTTP_ADDR)
    http_service.setServiceParent(top_service)

    top_service.startService()

    reactor.addSystemEventTrigger('before', 'shutdown', top_service.stopService)

    reactor.run() 
Example #2
Source File: twisted.py    From tornado-zh with MIT License 6 votes vote down vote up
def __init__(self, io_loop=None):
        if not io_loop:
            io_loop = tornado.ioloop.IOLoop.current()
        self._io_loop = io_loop
        self._readers = {}  # map of reader objects to fd
        self._writers = {}  # map of writer objects to fd
        self._fds = {}  # a map of fd to a (reader, writer) tuple
        self._delayedCalls = {}
        PosixReactorBase.__init__(self)
        self.addSystemEventTrigger('during', 'shutdown', self.crash)

        # IOLoop.start() bypasses some of the reactor initialization.
        # Fire off the necessary events if they weren't already triggered
        # by reactor.run().
        def start_if_necessary():
            if not self._started:
                self.fireSystemEvent('startup')
        self._io_loop.add_callback(start_if_necessary)

    # IReactorTime 
Example #3
Source File: __init__.py    From bugbuzz-python with MIT License 6 votes vote down vote up
def _request_async(self, request, callback=None, error=None, single=False, timeout=5):
        global _urllib_request
        ## Build URL
        url = self.getUrl(request)
        if single is True:
            id = time.time()
            client = HTTPClient(self, url=url, urllib_func=_urllib_request,
                                callback=None, error=None, id=id, timeout=timeout)
            with self.latest_sub_callback_lock:
                self.latest_sub_callback['id'] = id
                self.latest_sub_callback['callback'] = callback
                self.latest_sub_callback['error'] = error
        else:
            client = HTTPClient(self, url=url, urllib_func=_urllib_request,
                                callback=callback, error=error, timeout=timeout)

        thread = threading.Thread(target=client.run)
        thread.daemon = self.daemon
        thread.start()

        def abort():
            client.cancel()
        return abort 
Example #4
Source File: __init__.py    From arnold-usd with Apache License 2.0 6 votes vote down vote up
def run(self, app): # pragma: no cover
        from wsgiref.simple_server import WSGIRequestHandler, WSGIServer
        from wsgiref.simple_server import make_server
        import socket

        class FixedHandler(WSGIRequestHandler):
            def address_string(self): # Prevent reverse DNS lookups please.
                return self.client_address[0]
            def log_request(*args, **kw):
                if not self.quiet:
                    return WSGIRequestHandler.log_request(*args, **kw)

        handler_cls = self.options.get('handler_class', FixedHandler)
        server_cls  = self.options.get('server_class', WSGIServer)

        if ':' in self.host: # Fix wsgiref for IPv6 addresses.
            if getattr(server_cls, 'address_family') == socket.AF_INET:
                class server_cls(server_cls):
                    address_family = socket.AF_INET6

        srv = make_server(self.host, self.port, app, server_cls, handler_cls)
        srv.serve_forever() 
Example #5
Source File: __init__.py    From arnold-usd with Apache License 2.0 6 votes vote down vote up
def run(self):
        exists = os.path.exists
        mtime = lambda path: os.stat(path).st_mtime
        files = dict()

        for module in list(sys.modules.values()):
            path = getattr(module, '__file__', '')
            if path[-4:] in ('.pyo', '.pyc'): path = path[:-1]
            if path and exists(path): files[path] = mtime(path)

        while not self.status:
            if not exists(self.lockfile)\
            or mtime(self.lockfile) < time.time() - self.interval - 5:
                self.status = 'error'
                thread.interrupt_main()
            for path, lmtime in list(files.items()):
                if not exists(path) or mtime(path) > lmtime:
                    self.status = 'reload'
                    thread.interrupt_main()
                    break
            time.sleep(self.interval) 
Example #6
Source File: twisted.py    From tornado-zh with MIT License 6 votes vote down vote up
def __init__(self, io_loop=None):
        if not io_loop:
            io_loop = tornado.ioloop.IOLoop.current()
        self._io_loop = io_loop
        self._readers = {}  # map of reader objects to fd
        self._writers = {}  # map of writer objects to fd
        self._fds = {}  # a map of fd to a (reader, writer) tuple
        self._delayedCalls = {}
        PosixReactorBase.__init__(self)
        self.addSystemEventTrigger('during', 'shutdown', self.crash)

        # IOLoop.start() bypasses some of the reactor initialization.
        # Fire off the necessary events if they weren't already triggered
        # by reactor.run().
        def start_if_necessary():
            if not self._started:
                self.fireSystemEvent('startup')
        self._io_loop.add_callback(start_if_necessary)

    # IReactorTime 
Example #7
Source File: Start.py    From Timeline with GNU General Public License v3.0 6 votes vote down vote up
def main():
    global SERVERS

    # Example of initiating server to listen to given endpoint.
    '''
    LOGIN_SERVER => Initiates Engine to be a Login server
    WORLD_SERVER => Initiates Engine to be a World Server

    The type of server *must* be sent to Engine as a parameter!
    '''
    # CROSS_PROTOCOL = Accepts both AS2 + AS3 under one roof

    LoginServer = Engine(Penguin, Constants.LOGIN_SERVER, 1, "Login", server_protocol=Constants.CROSS_PROTOCOL)
    Gravity = Engine(Penguin, Constants.WORLD_SERVER, 100, "Gravity", server_protocol=Constants.CROSS_PROTOCOL)

    LoginServer.run('127.0.0.1', 6112)
    Gravity.run('127.0.0.1', 9875)

    SERVERS += [LoginServer, Gravity] 
Example #8
Source File: test_coinswap.py    From CoinSwapCS with GNU General Public License v3.0 6 votes vote down vote up
def runcase(alice_class, carol_class, fail_alice_state=None, fail_carol_state=None):
    options_server = Options()
    wallets = make_wallets(num_alices + 1,
                               wallet_structures=wallet_structures,
                               mean_amt=funding_amount)
    args_server = ["dummy"]
    test_data_server = (wallets[num_alices]['seed'], args_server, options_server,
                        False, None, carol_class, None, fail_carol_state)
    carol_bbmb = main_cs(test_data_server)
    options_alice = Options()
    options_alice.serve = False
    alices = []
    for i in range(num_alices):
        args_alice = ["dummy", amounts[i]]
        if dest_addr:
            args_alice.append(dest_addr)
        test_data_alice = (wallets[i]['seed'], args_alice, options_alice, False,
                           alice_class, None, fail_alice_state, None)
        alices.append(main_cs(test_data_alice))
    l = task.LoopingCall(miner)
    reactor.callWhenRunning(start_mining, l)
    reactor.run()
    return (alices, carol_bbmb, wallets[num_alices]['wallet']) 
Example #9
Source File: __init__.py    From arnold-usd with Apache License 2.0 6 votes vote down vote up
def run(self, handler): # pragma: no cover
        import fapws._evwsgi as evwsgi
        from fapws import base, config
        port = self.port
        if float(config.SERVER_IDENT[-2:]) > 0.4:
            # fapws3 silently changed its API in 0.5
            port = str(port)
        evwsgi.start(self.host, port)
        # fapws3 never releases the GIL. Complain upstream. I tried. No luck.
        if 'BOTTLE_CHILD' in os.environ and not self.quiet:
            _stderr("WARNING: Auto-reloading does not work with Fapws3.\n")
            _stderr("         (Fapws3 breaks python thread support)\n")
        evwsgi.set_base_module(base)
        def app(environ, start_response):
            environ['wsgi.multiprocess'] = False
            return handler(environ, start_response)
        evwsgi.wsgi_cb(('', app))
        evwsgi.run() 
Example #10
Source File: imapclient.py    From bitmask-dev with GNU General Public License v3.0 6 votes vote down vote up
def main():
    hostname = raw_input('IMAP4 Server Hostname: ')
    port = raw_input('IMAP4 Server Port (the default is 143): ')
    username = raw_input('IMAP4 Username: ')
    password = util.getPassword('IMAP4 Password: ')

    onConn = defer.Deferred(
    ).addCallback(cbServerGreeting, username, password
                  ).addErrback(ebConnection
                               ).addBoth(cbClose)

    factory = SimpleIMAP4ClientFactory(username, onConn)

    from twisted.internet import reactor
    conn = reactor.connectTCP(hostname, int(port), factory)
    reactor.run() 
Example #11
Source File: worker.py    From worker with GNU General Public License v3.0 6 votes vote down vote up
def main(number):

    def get_metrics():
        return [
            ("checker.time.%s.%s" %
             (config.HOSTNAME,
              number),
                spy.TRIGGER_CHECK.get_metrics()["sum"]),
            ("checker.triggers.%s.%s" %
             (config.HOSTNAME,
              number),
                spy.TRIGGER_CHECK.get_metrics()["count"]),
            ("checker.errors.%s.%s" %
             (config.HOSTNAME,
              number),
                spy.TRIGGER_CHECK_ERRORS.get_metrics()["count"])]

    graphite.sending(get_metrics)

    def start(db):
        checker = TriggersCheck(db)
        checker.start()
        reactor.addSystemEventTrigger('before', 'shutdown', checker.stop)

    run(start) 
Example #12
Source File: twistedtools.py    From locality-sensitive-hashing with MIT License 6 votes vote down vote up
def threaded_reactor():
    """
    Start the Twisted reactor in a separate thread, if not already done.
    Returns the reactor.
    The thread will automatically be destroyed when all the tests are done.
    """
    global _twisted_thread
    try:
        from twisted.internet import reactor
    except ImportError:
        return None, None
    if not _twisted_thread:
        from twisted.python import threadable
        from threading import Thread
        _twisted_thread = Thread(target=lambda: reactor.run( \
                installSignalHandlers=False))
        _twisted_thread.setDaemon(True)
        _twisted_thread.start()
    return reactor, _twisted_thread

# Export global reactor variable, as Twisted does 
Example #13
Source File: pointBot.py    From IRCBots with MIT License 6 votes vote down vote up
def userCommands(self, nick, message):
        if message == "help":
            if (time() - self.lastHelp) > 20:
                print("Admin Commands: start, stop, auto, reset, save, restore, say <msg>, me <action>, msg <nick> <msg>, status <user>, setpts <user/all> <points>, setgp <user/all> <gp>, ignore <user>, unignore <user>")
                self.msg(self.channel, "User Commands: help, rules, points, [e.g. pointBot, help]. PM anything for your status.")
                self.msg(self.channel, "Point Exchanges: +/-<pts> [to] <user> [reason] (e.g. +1 to user for being awesome)")
                self.lastHelp = time()
        elif message == "rules":
            if (time() - self.lastRules) > 20:
                self.msg(self.channel, "Hello, it's me, pointBot. I keep track of +s and -s handed out in the IRC. " +
                     "You get 10 points to give away every day, and these points are refreshed every morning at 8 AM. " +
                     "Using bots is not allowed. If you run into any issues, talk to the admin (J. Long). " +
                     "Have a day.")
                self.lastRules = time()
        elif message == "points":
            if (time() - self.lastPoints) > 20:
                self.displayPoints()
                self.lastPoints = time()
        return 
Example #14
Source File: __init__.py    From bugbuzz-python with MIT License 6 votes vote down vote up
def _request_async(self, request, callback=None, error=None, single=False, timeout=5):
        global _urllib_request
        ## Build URL
        url = self.getUrl(request)
        if single is True:
            id = time.time()
            client = HTTPClient(self, url=url, urllib_func=_urllib_request,
                                callback=None, error=None, id=id, timeout=timeout)
            with self.latest_sub_callback_lock:
                self.latest_sub_callback['id'] = id
                self.latest_sub_callback['callback'] = callback
                self.latest_sub_callback['error'] = error
        else:
            client = HTTPClient(self, url=url, urllib_func=_urllib_request,
                                callback=callback, error=error, timeout=timeout)

        thread = threading.Thread(target=client.run)
        thread.daemon = self.daemon
        thread.start()

        def abort():
            client.cancel()
        return abort 
Example #15
Source File: __init__.py    From arnold-usd with Apache License 2.0 5 votes vote down vote up
def run(self, handler): # pragma: no cover
        from wsgiref.handlers import CGIHandler
        def fixed_environ(environ, start_response):
            environ.setdefault('PATH_INFO', '')
            return handler(environ, start_response)
        CGIHandler().run(fixed_environ) 
Example #16
Source File: __init__.py    From arnold-usd with Apache License 2.0 5 votes vote down vote up
def run(self, handler): # pragma: no cover
        import flup.server.fcgi
        self.options.setdefault('bindAddress', (self.host, self.port))
        flup.server.fcgi.WSGIServer(handler, **self.options).run() 
Example #17
Source File: websockets.py    From python-binance with MIT License 5 votes vote down vote up
def run(self):
        try:
            reactor.run(installSignalHandlers=False)
        except ReactorAlreadyRunning:
            # Ignore error about reactor already running
            pass 
Example #18
Source File: __init__.py    From arnold-usd with Apache License 2.0 5 votes vote down vote up
def run(self, handler):
        from waitress import serve
        serve(handler, host=self.host, port=self.port) 
Example #19
Source File: __init__.py    From arnold-usd with Apache License 2.0 5 votes vote down vote up
def run(self, handler): # pragma: no cover
        from paste import httpserver
        from paste.translogger import TransLogger
        handler = TransLogger(handler, setup_console_handler=(not self.quiet))
        httpserver.serve(handler, host=self.host, port=str(self.port),
                         **self.options) 
Example #20
Source File: __init__.py    From arnold-usd with Apache License 2.0 5 votes vote down vote up
def run(self, handler):
        for sa in self.adapters:
            try:
                return sa(self.host, self.port, **self.options).run(handler)
            except ImportError:
                pass 
Example #21
Source File: server.py    From pyvpn with The Unlicense 5 votes vote down vote up
def main():
    # TUN dev
    tundev = TunDevice(reactor)
    tundev.ifconfig('192.168.10.3', '255.255.255.240')
    tundev.startReading()
    # tcp for client
    serverfactory = VPNFactory(tundev)
    reactor.listenTCP(1234, serverfactory)  # @UndefinedVariable
    # web console
    reactor.listenTCP(8080, webconsole.factory)  # @UndefinedVariable
    # run
    reactor.run()  # @UndefinedVariable 
Example #22
Source File: __init__.py    From arnold-usd with Apache License 2.0 5 votes vote down vote up
def run(self, handler): # pragma: no cover
        pass 
Example #23
Source File: __init__.py    From arnold-usd with Apache License 2.0 5 votes vote down vote up
def run(self, **kwargs):
        ''' Calls :func:`run` with the same parameters. '''
        run(self, **kwargs) 
Example #24
Source File: __init__.py    From arnold-usd with Apache License 2.0 5 votes vote down vote up
def run(self, handler):
        from gevent import wsgi, pywsgi, local
        if not isinstance(threading.local(), local.local):
            msg = "Bottle requires gevent.monkey.patch_all() (before import)"
            raise RuntimeError(msg)
        if not self.options.pop('fast', None): wsgi = pywsgi
        self.options['log'] = None if self.quiet else 'default'
        address = (self.host, self.port)
        server = wsgi.WSGIServer(address, handler, **self.options)
        if 'BOTTLE_CHILD' in os.environ:
            import signal
            signal.signal(signal.SIGINT, lambda s, f: server.stop())
        server.serve_forever() 
Example #25
Source File: online.py    From scrapy-cluster with MIT License 5 votes vote down vote up
def test_crawler_process(self):
        runner = CrawlerRunner(self.settings)
        d = runner.crawl(CustomSpider)
        d.addBoth(lambda _: reactor.stop())
        # add crawl to redis
        key = "test-spider:dmoztools.net:queue"
        self.redis_conn.zadd(key, self.example_feed, -99)

        # run the spider, give 20 seconds to see the url, crawl it,
        # and send to kafka. Then we kill the reactor
        def thread_func():
            time.sleep(20)
            reactor.stop()

        thread = threading.Thread(target=thread_func)
        thread.start()
        reactor.run()

        message_count = 0
        m = next(self.consumer)

        if m is None:
            pass
        else:
            the_dict = json.loads(m.value)
            if the_dict is not None and the_dict['appid'] == 'test' \
                    and the_dict['crawlid'] == 'abc12345':
                message_count += 1

        self.assertEquals(message_count, 1) 
Example #26
Source File: vtp.py    From hack4career with Apache License 2.0 5 votes vote down vote up
def vtproxy():
	reactor.listenTCP(lport, portforward.ProxyFactory(dhost, dport))
	reactor.run() 
Example #27
Source File: telnet_honeypot.py    From hack4career with Apache License 2.0 5 votes vote down vote up
def main():
    factory = Factory()
    factory.protocol = lambda: Shell()
    reactor.listenTCP(2323, factory)
    reactor.run() 
Example #28
Source File: twisted_handler.py    From liaar with MIT License 5 votes vote down vote up
def start():
    root = SiteResource()
    factory = Site(root)
    reactor.listenTCP(setting.LIAAR_PORT, factory)
    logger.info('Liaar is available on port %d' % setting.LIAAR_PORT)
    # run the twisted
    reactor.run() 
Example #29
Source File: LonnieBot.py    From IRCBots with MIT License 5 votes vote down vote up
def main():
    f = protocol.ClientFactory()
    f.protocol = lonnieBot

    reactor.connectTCP(serv_ip, serv_port, f)
    reactor.run() 
Example #30
Source File: hulk.py    From IRCBots with MIT License 5 votes vote down vote up
def main():
    f = protocol.ReconnectingClientFactory()
    f.protocol = Hulk

    reactor.connectTCP(serv_ip, serv_port, f)
    reactor.run()