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.

112 Examples 7

Example 1

Project: twisted-intro Source File: get-poetry-broken.py
Function: poetry_main
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 2

Project: worker Source File: worker.py
Function: run
def run(callback):

    db = Db()
    datalib.db = db
    init = db.startService()
    init.addCallback(callback)

    reactor.run()

Example 3

Project: Community-Zenpacks Source File: SQLClient.py
Function: sqlget
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 4

Project: envisage Source File: twisted_application.py
Function: start
    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 5

Project: Subspace Source File: subspace-cli.py
Function: get_messages
    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 6

Project: foolscap Source File: tail.py
Function: run
    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 7

Project: bitmask_client Source File: backend.py
    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.")

Example 8

Project: quarry Source File: server_auth.py
Function: main
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 9

Project: twimp Source File: live_publish_client.py
Function: run
def run(url, stream_name='livestream', audio_codec=None, video_codec=None,
        audio_bitrate=64, video_bitrate=400, samplerate=44100,
        framerate=Fraction('15/1'), channels=1,
        width=320, height=240, keyframe_interval=5.0, view=False,
        view_window=None):
    src = NewGstSource(audio_bitrate, video_bitrate,
                       samplerate, channels, framerate, width, height,
                       keyframe_interval, audio_codec=audio_codec,
                       video_codec=video_codec, view=view,
                       view_window=view_window)
    f = connect_client_factory(url, OneTimeAppFactory,
                               SimplePublishingApp,
                               src,
                               stream_name)
    reactor.run()

Example 10

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

Example 11

Project: deluge Source File: server.py
Function: start
    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 12

Project: Subspace Source File: subspace-cli.py
Function: get_info
    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 13

Project: vertex Source File: q2qclient.py
    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 14

Project: django-dynamic-scraper Source File: scraper_test.py
    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 15

Project: quarry Source File: client_ping.py
Function: main
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 16

Project: mythbox Source File: manhole.py
Function: run
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 17

Project: ants Source File: transporttest.py
    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 18

Project: pyorpg-client Source File: engine.py
    def init(self):
        ResourceManager.loadEverything()
        g.soundEngine = SoundEngine()
        g.soundEngine.loadSounds()

        self.initConfig(g.dataPath + '/config.cfg')

        self.setState(MENU_LOGIN)

        pygame.display.flip()
        self.gameLoop()
        reactor.run()

Example 19

Project: scrapyrt Source File: cmdline.py
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 20

Project: socorro Source File: sb_pop3dnd.py
def start():
    assert state.prepared, "Must prepare before starting"
    # The asyncore stuff doesn't play nicely with twisted (or vice-versa),
    # so put them in separate threads.
    thread.start_new_thread(Dibbler.run, ())
    reactor.run()

Example 21

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

Example 22

Project: snmposter Source File: snmposter.py
    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 23

Project: scrapyd Source File: script.py
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 24

Project: Subspace Source File: subspace-cli.py
Function: get_new
    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 25

Project: locality-sensitive-hashing Source File: twistedtools.py
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 26

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

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

Example 27

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

Example 28

Project: kamaelia_ Source File: RawServer_twisted.py
    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 29

Project: djangobot Source File: client.py
Function: run
    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 30

Project: quarry Source File: client_messenger.py
Function: main
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 31

Project: frikanalen Source File: run_queue.py
    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 32

Project: woid Source File: top.py
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 33

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

    logging.basicConfig(level=logging.NOTSET)

    class TestClient(CampfireClient):
        pass

    t = TestClient()
    t.connect()

    reactor.run()

Example 34

Project: pinder Source File: streaming.py
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 35

Project: mythbox Source File: stdio.py
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 36

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

Example 37

Project: lbry Source File: node_rpc_cli.py
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 38

Project: quarry Source File: proxy_hide_chat.py
Function: main
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 39

Project: Firefly Source File: server.py
Function: start
    def start(self):
        '''启动服务器
        '''
        log.msg('%s start...'%self.servername)
        log.msg('%s pid: %s'%(self.servername,os.getpid()))
        reactor.run()

Example 40

Project: ants Source File: webservicetest.py
    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 41

Project: sydent Source File: sydent.py
Function: run
    def run(self):
        self.clientApiHttpServer.setup()
        self.replicationHttpsServer.setup()
        self.pusher.setup()

        if self.pidfile:
            with open(self.pidfile, 'w') as pidfile:
                pidfile.write(str(os.getpid()) + "\n")

        twisted.internet.reactor.run()

Example 42

Project: pyrf Source File: simple_gui.py
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 43

Project: worker Source File: converter.py
Function: run
def run():

    config.read()
    config.LOG_DIRECTORY = "stdout"
    log.startLogging(sys.stdout)

    db = Db()
    db.startService().addCallback(convert)

    reactor.run()

Example 44

Project: PiIO.WS Source File: client.py
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 45

Project: quarry Source File: server_downtime.py
Function: main
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 46

Project: pixelated-user-agent Source File: app_test_client.py
    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 47

Project: beatserver Source File: server.py
    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 48

Project: quarry Source File: client_chat_logger.py
Function: main
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 49

Project: b2bua Source File: Rtp_proxy_client_udp.py
Function: run
    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 50

Project: datasift-python Source File: client.py
Function: stream
    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()
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3