twisted.internet.reactor.run

Here are the examples of the python api twisted.internet.reactor.run taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

167 Examples 7

Example 1

View license
    def run_on_a_thread(self, logfile='/tmp/app_test_client.log', port=4567, host='127.0.0.1'):
        def _start():
            self.listenTCP(port, host)
            reactor.run()
        process = multiprocessing.Process(target=_start)
        process.start()
        time.sleep(1)
        return lambda: process.terminate()

Example 2

Project: pyrf
Source File: simple_gui.py
View license
def main():
    name = None
    if '-v' in sys.argv:
        sys.argv.remove('-v')
        logging.basicConfig(level=logging.DEBUG)
    if '-d' in sys.argv:
        d_index = sys.argv.index('-d')
        name = sys.argv[d_index + 1]
        del sys.argv[d_index:d_index + 2]
    app = QtGui.QApplication(sys.argv)
    qt4reactor.install() # requires QApplication to exist
    # requires qt4reactor to be installed
    if name:
        ex = MainWindow(open(name, 'wb'))
    else:
        ex = MainWindow()
    # late import because installReactor is being used
    from twisted.internet import reactor
    reactor.run()

Example 3

Project: beatserver
Source File: server.py
View license
    def run(self):
        """
        extract all schedules from beat_config files and feed into twisted task.
        """
        for beat in self.beat_config:
            message = self.beat_config[beat]['message']
            channel_name = self.beat_config[beat]['channel_name']
            schedule = self.beat_config[beat]['schedule']
            sche = task.LoopingCall(self.run_task, channel_name, message)
            sche.start(schedule.total_seconds())
        logger.info("beatserver started")
        reactor.run()

Example 4

Project: pinder
Source File: streaming.py
View license
def start(username, password, room_id, callback, errback, start_reactor=False):
    auth_header = 'Basic ' + base64.b64encode("%s:%s" % (username, password)).strip()
    url = 'https://streaming.campfirenow.com/room/%s/live.json' % room_id
    headers = Headers({
        'User-Agent': [USER_AGENT],
        'Authorization': [auth_header]})

    # issue the request
    agent = Agent(reactor)
    d = agent.request('GET', url, headers, None)
    d.addCallback(_get_response, callback, errback)
    d.addBoth(_shutdown, errback)
    if start_reactor:
      reactor.run()

Example 5

Project: scrapyrt
Source File: cmdline.py
View license
def execute():
    sys.path.insert(0, os.getcwd())
    arguments = parse_arguments()
    if arguments.settings:
        settings.setmodule(arguments.settings)
    if arguments.set:
        for name, value in arguments.set:
            settings.set(name.upper(), value)
    settings.set('PROJECT_SETTINGS', find_scrapy_project(arguments.project))
    settings.freeze()
    setup_logging()
    application = get_application(arguments)
    app.startApplication(application, save=False)
    reactor.run()

Example 6

Project: scrapyd
Source File: script.py
View license
def execute():
    try:
        config = _get_config()
    except NotConfigured:
        config = None
    log.startLogging(sys.stderr)
    application = get_application(config)
    app.startApplication(application, False)
    reactor.run()

Example 7

Project: quarry
Source File: client_chat_logger.py
View license
def main(argv):
    parser = ProfileCLI.make_parser()
    parser.add_argument("host")
    parser.add_argument("-p", "--port", default=25565, type=int)
    args = parser.parse_args(argv)

    run(args)
    reactor.run()

Example 8

Project: quarry
Source File: client_messenger.py
View license
def main(argv):
    parser = ProfileCLI.make_parser()
    parser.add_argument("host")
    parser.add_argument("port", nargs='?', default=25565, type=int)
    args = parser.parse_args(argv)

    run(args)
    reactor.run()

Example 9

Project: quarry
Source File: client_ping.py
View license
def main(argv):
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("host")
    parser.add_argument("-p", "--port", default=25565, type=int)
    args = parser.parse_args(argv)

    factory = PingFactory()
    factory.connect(args.host, args.port, "status")
    reactor.run()

Example 10

Project: quarry
Source File: client_player_list.py
View license
def main(argv):
    parser = ProfileCLI.make_parser()
    parser.add_argument("host")
    parser.add_argument("-p", "--port", default=25565, type=int)
    args = parser.parse_args(argv)

    run(args)
    reactor.run()

Example 11

Project: quarry
Source File: proxy_hide_chat.py
View license
def main(argv):
    # Parse options
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("-a", "--listen-host", default="", help="address to listen on")
    parser.add_argument("-p", "--listen-port", default=25565, type=int, help="port to listen on")
    parser.add_argument("-b", "--connect-host", default="127.0.0.1", help="address to connect to")
    parser.add_argument("-q", "--connect-port", default=25565, type=int, help="port to connect to")
    args = parser.parse_args(argv)

    # Create factory
    factory = QuietDownstreamFactory()
    factory.motd = "Proxy Server"
    factory.connect_host = args.connect_host
    factory.connect_port = args.connect_port

    # Listen
    factory.listen(args.listen_host, args.listen_port)
    reactor.run()

Example 12

Project: quarry
Source File: server_auth.py
View license
def main(argv):
    # Parse options
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("-a", "--host", default="", help="address to listen on")
    parser.add_argument("-p", "--port", default=25565, type=int, help="port to listen on")
    args = parser.parse_args(argv)

    # Create factory
    factory = AuthFactory()

    # Listen
    factory.listen(args.host, args.port)
    reactor.run()

Example 13

Project: quarry
Source File: server_downtime.py
View license
def main(argv):
    # Parse options
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("-a", "--host", default="", help="address to listen on")
    parser.add_argument("-p", "--port", default=25565, type=int, help="port to listen on")
    parser.add_argument("-m", "--message", default="We're down for maintenance",
                        help="message to kick users with")
    args = parser.parse_args(argv)

    # Create factory
    factory = DowntimeFactory()
    factory.motd = args.message

    # Listen
    factory.listen(args.host, args.port)
    reactor.run()

Example 14

Project: nodeset.core
Source File: pure.py
View license
def client():
    
    stats = Stats()
    c = protocol.ClientCreator(reactor, DumbProto)
    c.connectTCP("localhost", 5333).addCallback(gotProtocol, stats, 3000)     
     
    reactor.run()

Example 15

View license
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

Example 16

Project: b2bua
Source File: Rtp_proxy_client_udp.py
View license
    def run(self):
        import os
        from twisted.internet import reactor
        global_config = {}
        global_config['my_pid'] = os.getpid()
        rtpc = Rtp_proxy_client_udp(global_config, ('127.0.0.1', 22226), None)
        rtpc.rtpp_class = Rtp_proxy_client_udp
        os.system('sockstat | grep -w %d' % global_config['my_pid'])
        rtpc.send_command('Ib', self.gotreply)
        reactor.run()
        rtpc.reconnect(('localhost', 22226), ('0.0.0.0', 34222))
        os.system('sockstat | grep -w %d' % global_config['my_pid'])
        rtpc.send_command('V', self.gotreply)
        reactor.run()
        rtpc.reconnect(('localhost', 22226), ('127.0.0.1', 57535))
        os.system('sockstat | grep -w %d' % global_config['my_pid'])
        rtpc.send_command('V', self.gotreply)
        reactor.run()
        rtpc.shutdown()

Example 17

Project: kamaelia_
Source File: RawServer_twisted.py
View license
    def listen_forever(self):
        self.ident = thread.get_ident()
        if self.listened:
            UnimplementedWarning(_("listen_forever() should only be called once per reactor."))
        self.listened = 1
        
        l = task.LoopingCall(self.stop)
        l.start(1)#, now = False)
        
        if noSignals:
            reactor.run(installSignalHandlers=False)
        else:
            reactor.run()

Example 18

Project: vertex
Source File: q2qclient.py
View license
    def start(self, portno=None):
        import sys
        lfname = self['logfile']
        if lfname == '-':
            lf = sys.stdout
        else:
            lf = file(os.path.expanduser(lfname), 'ab+')
        log.startLogging(lf,
                         setStdout=False)
        srv = self.getService()
        from twisted.application.app import startApplication
        startApplication(srv, False)
        reactor.run()

Example 19

Project: woid
Source File: top.py
View license
def main():
    service_crawlers = (
        (crawlers.RedditCrawler(), FIVE_MINUTES),
        (crawlers.MediumCrawler(), FIVE_MINUTES),
        (crawlers.DiggCrawler(), FIVE_MINUTES),
        (crawlers.HackerNewsCrawler(), FIVE_MINUTES),
        (crawlers.GithubCrawler(), THIRTY_MINUTES),
        (crawlers.NyTimesCrawler(), THIRTY_MINUTES)
        )

    for crawler in service_crawlers:
        task.LoopingCall(crawler[0].run).start(crawler[1])

    reactor.run()

Example 20

Project: foolscap
Source File: tail.py
View license
    def run(self, target_furl):
        target_tubid = SturdyRef(target_furl).getTubRef().getTubID()
        d = fireEventually(target_furl)
        d.addCallback(self.start, target_tubid)
        d.addErrback(self._error)
        print "starting.."
        reactor.run()

Example 21

Project: foolscap
Source File: web.py
View license
    def run(self, options):
        d = fireEventually(options)
        d.addCallback(self.start)
        d.addErrback(self._error)
        print "starting.."
        reactor.run()

Example 22

Project: ants
Source File: transporttest.py
View license
    def test(self):
        setting = settings.Settings()
        cluster = node.NodeManager(setting)
        transport_test = transport.TransportManager(cluster)
        ip = '127.0.0.1'
        transport_test.run_server()
        transport_test.run_client(ip, setting.get('TRANSPORT_PORT'))
        SendRequestThread(transport_test, ip).start()
        reactor.run()

Example 23

Project: ants
Source File: webservicetest.py
View license
    def test(self):
        cluster_info = cluster.ClusterInfo(name='test')
        setting = settings.Settings()
        crawl_manager = crawl.CrawlManager(setting, cluster_info)
        web_service_management = webservice.WebServiceManager(8080, cluster_info, crawl_manager)
        web_service_management.start()
        reactor.run()

Example 24

Project: Community-Zenpacks
Source File: SQLClient.py
View license
def SQLGet(cs, query, columns):
    from SQLPlugin import SQLPlugin
    sp = SQLPlugin()
    sp.tables = {'t': (query, {}, cs, columns)}
    cl = SQLClient(device=None, plugins=[sp,])
    cl.run()
    reactor.run()
    for plugin, result in cl.getResults():
        if plugin == sp and 't' in result:
            return result['t']
    return result

Example 25

Project: PiIO.WS
Source File: client.py
View license
def main():
    if USE_SSL:
        uri_type = "wss"
    else:
        uri_type = "ws"

    server_url = "%s://%s:%d/rpi/" % (uri_type, SERVER, PORT)

    if DEBUG:
        log.startLogging(sys.stdout)

    #factory = WebSocketClientFactory(server_url, useragent=settings.RPI_USER_AGENT, debug=DEBUG)
    factory = ReconnectingWebSocketClientFactory(server_url, useragent=settings.RPI_USER_AGENT, debug=DEBUG)
    factory.protocol = RPIClientProtocol

    connectWS(factory)
    reactor.run()

Example 26

Project: gemuo
Source File: simple.py
View license
def simple_run(run):
    d = simple_login()
    d.addCallback(run)
    d.addCallback(simple_callback)
    d.addErrback(simple_err)
    reactor.run()

Example 27

Project: snmposter
Source File: snmposter.py
View license
    def start(self):
        for a in self.agents:
            print "Starting %s on %s." % (a['filename'], a['ip'])
            if os.uname()[0] == 'Darwin':
                os.popen("ifconfig lo0 alias %s up" % (a['ip'],))
            elif os.uname()[0] == 'Linux':
                os.popen("/sbin/ip addr add %s dev lo" % (a['ip'],))
            else:
                print "WARNING: Unable to add loopback alias on this platform."

            faker = SNMPoster(a['ip'], a['filename'])
            faker.run()

        daemonize()
        reactor.run()

Example 28

Project: Subspace
Source File: subspace-cli.py
View license
    def getmessages(self):
        parser = argparse.ArgumentParser(
            description='Returns a list of your messages in json format',
            usage='''usage:
    subspace getmessages''')
        args = parser.parse_args(sys.argv[2:])
        d = proxy.callRemote('getmessages')
        d.addCallbacks(printValue, printError)
        reactor.run()

Example 29

Project: Subspace
Source File: subspace-cli.py
View license
    def getnew(self):
        parser = argparse.ArgumentParser(
            description="Returns messages that have not previously been returned by this command",
            usage='''usage:
    subspace getnew''')
        args = parser.parse_args(sys.argv[2:])
        d = proxy.callRemote('getnew')
        d.addCallbacks(printValue, printError)
        reactor.run()

Example 30

Project: Subspace
Source File: subspace-cli.py
View license
    def getinfo(self):
        parser = argparse.ArgumentParser(
            description="Returns an object containing various state info",
            usage='''usage:
    subspace getinfo''')
        args = parser.parse_args(sys.argv[2:])
        d = proxy.callRemote('getinfo')
        d.addCallbacks(printValue, printError)
        reactor.run()

Example 31

Project: gateway
Source File: gateway.py
View license
def main(service):
    application = GatewayApplication(service)
    tornado.autoreload.start(ioloop)
    application.listen(config.get('websocket-port', 8888))
    #debug_console = DebugConsole(application)
    reactor.run()

Example 32

Project: datasift-python
Source File: client.py
View license
    def _stream(self):  # pragma: no cover
        """Runs in a sub-process to perform stream consumption"""
        self.factory.protocol = LiveStream
        self.factory.datasift = {
            'on_open': self._on_open,
            'on_close': self._on_close,
            'on_message': self._on_message,
            'send_message': None
        }
        if self.config.ssl:
            from twisted.internet import ssl
            options = ssl.optionsForClientTLS(hostname=WEBSOCKET_HOST.decode("utf-8"))
            connectWS(self.factory, options)
        else:
            connectWS(self.factory)
        reactor.run()

Example 33

Project: djangospider
Source File: async_twisted.py
View license
  def RunMain(self):
    try:

      heartbeat=task.LoopingCall(self.add_url)
      heartbeat.start(1)
      reactor.run()
    except KeyboardInterrupt:
      pass

Example 34

Project: deluge
Source File: server.py
View license
    def start(self):
        """
        Start the DelugeWeb server
        """
        if self.socket:
            log.warn('DelugeWeb is already running and cannot be started')
            return

        log.info('Starting webui server at PID %s', os.getpid())
        if self.https:
            self.start_ssl()
        else:
            self.start_normal()

        component.get('Web').enable()

        if self.daemon:
            reactor.run()

Example 35

Project: djangobot
Source File: client.py
View license
    def run(self):
        if self.isSecure:
            contextFactory = ssl.ClientContextFactory()
        else:
            contextFactory = None

        self.connector = connectWS(self, contextFactory)
        self.read_channel()
        reactor.run(installSignalHandlers=True)

Example 36

Project: envisage
Source File: twisted_application.py
View license
    def start(self):
        """ Start the application. """

        started = super(TwistedApplication, self).start()

        # Don't start the event loop if the start was vetoed.
        if started:
            from twisted.internet import reactor

            logger.debug('---------- reactor starting ----------')
            reactor.run()

        return started

Example 37

Project: frikanalen
Source File: run_queue.py
View license
    def handle(self, *args, **options):
        pending_tasks = Task.objects.filter(status=Task.STATE_PENDING)
        self.log.info("%d outstanding tasks" % (len(pending_tasks),))
        if pending_tasks:
            for task in pending_tasks:
                self.run_task(task)
            reactor.run()

Example 38

View license
    def run_checker_test(self, id):
        kwargs = {
        'id': id,
        }
        self.checker_test = CheckerTest(**kwargs)
        self.checker_test.conf['RUN_TYPE'] = 'TASK'
        self.checker_test.conf['DO_ACTION'] = True
        self.checker_test.conf['LOG_ENABLED'] = False
        self.checker_test.conf['LOG_LEVEL'] = 'DEBUG' 
        self.crawler.crawl(self.checker_test)
        self.crawler.start()
        log.start(loglevel="DEBUG", logstdout=True)
        reactor.run()

Example 39

Project: ibid
Source File: campfirewords.py
View license
def main():

    logging.basicConfig(level=logging.NOTSET)

    class TestClient(CampfireClient):
        pass

    t = TestClient()
    t.connect()

    reactor.run()

Example 40

Project: twisted-intro
Source File: get-poetry-broken.py
View license
def poetry_main():
    addresses = parse_args()

    start = datetime.datetime.now()

    sockets = [PoetrySocket(i + 1, addr) for i, addr in enumerate(addresses)]

    from twisted.internet import reactor
    reactor.run()

    elapsed = datetime.datetime.now() - start

    for i, sock in enumerate(sockets):
        print 'Task %d: %d bytes of poetry' % (i + 1, len(sock.poem))

    print 'Got %d poems in %s' % (len(addresses), elapsed)

Example 41

Project: twisted-intro
Source File: get-poetry-broken.py
View license
def poetry_main():
    addresses = parse_args()

    start = datetime.datetime.now()

    sockets = [PoetrySocket(i + 1, addr) for i, addr in enumerate(addresses)]

    from twisted.internet import reactor
    reactor.run()

    elapsed = datetime.datetime.now() - start

    for i, sock in enumerate(sockets):
        print 'Task %d: %d bytes of poetry' % (i + 1, len(sock.poem))

    print 'Got %d poems in %s' % (len(addresses), elapsed)

Example 42

Project: twisted-intro
Source File: get-poetry.py
View license
def poetry_main():
    addresses = parse_args()

    start = datetime.datetime.now()

    sockets = [PoetrySocket(i + 1, addr) for i, addr in enumerate(addresses)]

    from twisted.internet import reactor
    reactor.run()

    elapsed = datetime.datetime.now() - start

    for i, sock in enumerate(sockets):
        print 'Task %d: %d bytes of poetry' % (i + 1, len(sock.poem))

    print 'Got %d poems in %s' % (len(addresses), elapsed)

Example 43

Project: twisted-intro
Source File: get-poetry.py
View license
def poetry_main():
    addresses = parse_args()

    start = datetime.datetime.now()

    sockets = [PoetrySocket(i + 1, addr) for i, addr in enumerate(addresses)]

    from twisted.internet import reactor
    reactor.run()

    elapsed = datetime.datetime.now() - start

    for i, sock in enumerate(sockets):
        print 'Task %d: %d bytes of poetry' % (i + 1, len(sock.poem))

    print 'Got %d poems in %s' % (len(addresses), elapsed)

Example 44

Project: mythbox
Source File: stdio.py
View license
def runWithProtocol(klass):
    fd = sys.__stdin__.fileno()
    oldSettings = termios.tcgetattr(fd)
    tty.setraw(fd)
    try:
        p = ServerProtocol(klass)
        stdio.StandardIO(p)
        reactor.run()
    finally:
        termios.tcsetattr(fd, termios.TCSANOW, oldSettings)
        os.write(fd, "\r\x1bc\r")

Example 45

Project: mythbox
Source File: stdio.py
View license
def runWithProtocol(klass):
    fd = sys.__stdin__.fileno()
    oldSettings = termios.tcgetattr(fd)
    tty.setraw(fd)
    try:
        p = ServerProtocol(klass)
        stdio.StandardIO(p)
        reactor.run()
    finally:
        termios.tcsetattr(fd, termios.TCSANOW, oldSettings)
        os.write(fd, "\r\x1bc\r")

Example 46

Project: mythbox
Source File: manhole.py
View license
def run():
    config = MyOptions()
    try:
        config.parseOptions()
    except usage.UsageError, e:
        print str(e)
        print str(config)
        sys.exit(1)

    run_gtk2(config)

    from twisted.internet import reactor
    reactor.run()

Example 47

Project: mythbox
Source File: manhole.py
View license
def run():
    config = MyOptions()
    try:
        config.parseOptions()
    except usage.UsageError, e:
        print str(e)
        print str(config)
        sys.exit(1)

    run_gtk2(config)

    from twisted.internet import reactor
    reactor.run()

Example 48

Project: lbry
Source File: node_rpc_cli.py
View license
def main():
    parser = argparse.ArgumentParser(description="Send an rpc command to a dht node")
    parser.add_argument("rpc_command",
                        help="The rpc command to send to the dht node")
    parser.add_argument("--node_host",
                        help="The host of the node to connect to",
                        default="127.0.0.1")
    parser.add_argument("--node_port",
                        help="The port of the node to connect to",
                        default="8888")

    args = parser.parse_args()
    connect_string = 'http://%s:%s' % (args.node_host, args.node_port)
    proxy = Proxy(connect_string)

    d = proxy.callRemote(args.rpc_command)
    d.addCallbacks(print_value, print_error)
    d.addBoth(lambda _: shut_down())
    reactor.run()

Example 49

Project: lbry
Source File: node_rpc_cli.py
View license
def main():
    parser = argparse.ArgumentParser(description="Send an rpc command to a dht node")
    parser.add_argument("rpc_command",
                        help="The rpc command to send to the dht node")
    parser.add_argument("--node_host",
                        help="The host of the node to connect to",
                        default="127.0.0.1")
    parser.add_argument("--node_port",
                        help="The port of the node to connect to",
                        default="8888")

    args = parser.parse_args()
    connect_string = 'http://%s:%s' % (args.node_host, args.node_port)
    proxy = Proxy(connect_string)

    d = proxy.callRemote(args.rpc_command)
    d.addCallbacks(print_value, print_error)
    d.addBoth(lambda _: shut_down())
    reactor.run()

Example 50

Project: bitmask_client
Source File: backend.py
View license
    def run(self):
        """
        Start the ZMQ server and run the loop to handle requests.
        """
        self._signaler.start()
        self._frontend_checker = task.LoopingCall(self._check_frontend_alive)
        self._frontend_checker.start(self.PING_INTERVAL)
        logger.debug("Starting Twisted reactor.")
        reactor.run()
        logger.debug("Finished Twisted reactor.")