Esempio n. 1
0
def runEventLoop():
    global loop_running
    if not loop_running:
        event.init()
        event.signal(2, die)
        stackless.tasklet(eventLoop)()
        loop_running = True
Esempio n. 2
0
def main():
    logger.debug('IPPhone')
    logger.debug('開始')

    server_address = os.environ['SERVER_ADDRESS']
    config = {
        'server_address': (server_address, 5060),
        'local_uri': ('6002', server_address, 5061),
        'password': '******',
        'expires': 3600,
    }

    event.init()

    com.init()
    drv.init(config)
    reg.init(config)
    dialog.init(config)
    display.init()

    threading.Thread(target=drv.recv, daemon=True).start()
    threading.Thread(target=event.main, daemon=True).start()

    while cmd():
        pass

    logger.debug('終了')
Esempio n. 3
0
    def main(self, argv=sys.argv[1:], subclasses=None):
        """Run any Handler subclass in __main__ scope.
        """
        # XXX - even with only select enabled, BPF immediate doesn't
        # work on OSX, and we only get read events on full buffers.
        if sys.platform in ('darwin', 'win32'):
            os.putenv('EVENT_NOKQUEUE', '1')
            os.putenv('EVENT_NOPOLL', '1')

        if not subclasses:
            subclasses = find_subclasses(Handler, __import__('__main__'))
            if not subclasses:
                raise RuntimeError, 'no Handler subclasses found'

        event.init()
        self.setup()
        self.getopt(argv)

        # XXX - configure pcap filter
        global config
        config['pcap']['prefilter'] = ' '.join(self.args)

        for cls in subclasses:
            handlers[cls.name] = cls()
        for sig in (signal.SIGINT, signal.SIGTERM):
            event.signal(sig, event.abort)

        event.dispatch()

        for h in handlers.itervalues():
            h.teardown()
        self.teardown()
Esempio n. 4
0
def main():
    if len(sys.argv) > 1:
        url = sys.argv[1]
    else:
        url = 'http://localhost:8888/msgbus/chatdemo'

    scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
    if not path.startswith('/msgbus/'):
        raise ValueError, 'invalid msgbus URL: %s' % url
    channel = path[8:]
    username, password, hostname, port = parse_netloc(scheme, netloc)

    # XXX - stdin b0rkage!
    os.putenv('EVENT_NOKQUEUE', '1')
    os.putenv('EVENT_NOPOLL', '1')

    event.init()
    event.read(0, recv_stdin, channel)
    evmsg.open(hostname, port, scheme == 'https')
    if username and password:
        evmsg.set_auth(username, password)
    sub = evmsg.subscribe(channel, '*', '*', recv_chat)
    event.signal(2, event.abort)

    print 'pub/sub to', url
    event.dispatch()
Esempio n. 5
0
def main():
    if len(sys.argv) > 1:
        url = sys.argv[1]
    else:
        url = 'http://localhost:8888/msgbus/chatdemo'

    scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
    if not path.startswith('/msgbus/'):
        raise ValueError, 'invalid msgbus URL: %s' % url
    channel = path[8:]
    username, password, hostname, port = parse_netloc(scheme, netloc)

    # XXX - stdin b0rkage!
    os.putenv('EVENT_NOKQUEUE', '1')
    os.putenv('EVENT_NOPOLL', '1')
    
    event.init()
    event.read(0, recv_stdin, channel)
    evmsg.open(hostname, port, scheme == 'https')
    if username and password:
        evmsg.set_auth(username, password)
    sub = evmsg.subscribe(channel, '*', '*', recv_chat)
    event.signal(2, event.abort)

    print 'pub/sub to', url
    event.dispatch()
Esempio n. 6
0
def runEventLoop():
    global loop_running
    if not loop_running:
        event.init()
        event.signal(2, die)
        stackless.tasklet(eventLoop)()
        loop_running = True
Esempio n. 7
0
def runEventLoop():
    global loop_running
    if not loop_running:
        event.init()
        event.signal(2, die)
        event.signal(3, die)
        eventLoop()
        loop_running = True
Esempio n. 8
0
    def __init__(self):
        super(Hub, self).__init__()
        event.init()

        self.signal_exc_info = None
        self.signal(
            2,
            lambda signalnum, frame: self.greenlet.parent.throw(KeyboardInterrupt))
        self.events_to_add = []
Esempio n. 9
0
def test_event_once():
    expected = [('stub1', ('first', ))]

    event.init()
    event.regist('a', stub1)
    event.put('a', ('first', ))
    event.exec()

    assert result == expected
Esempio n. 10
0
 def init_pre_load(self, keep_keys=False):
     self.loading = True
     for u in physics.unit_update_list:
         u.deactivate()
     env.main_window.set_mouse_visible(False)
     physics.init()
     if not keep_keys:
         env.init()
     event.init()
Esempio n. 11
0
 def __init__(self, clock=time.time):
     event.init()
     self.clock = clock
     self.readers = {}
     self.writers = {}
     self.excs = {}
     self.greenlet = api.Greenlet(self.run)
     self.exc_info = None
     self.signal(2, lambda signalnum, frame: self.greenlet.parent.throw(KeyboardInterrupt))
Esempio n. 12
0
 def __init__(self, clock=time.time):
     event.init()
     self.clock = clock
     self.readers = {}
     self.writers = {}
     self.excs = {}
     self.greenlet = api.Greenlet(self.run)
     self.exc_info = None
     self.signal(
         2, lambda signalnum, frame: self.greenlet.parent.throw(
             KeyboardInterrupt))
Esempio n. 13
0
def init(events=False,
         event_val=1,
         logging_lvl=logging.INFO,
         n_module=('enet', 'socket'),
         s_module=('msgpack', 'json')):
    """Initialize network library.

    :param events: allow sending Pygame events (default False)
    :param event_val:
        set :const:`event.NETWORK` as
        :const:`pygame.USEREVENT` + :attr:`event_val` (default: 1)
    :param logging_lvl:
        level of logging messages (default :const:`logging.INFO`
        (see: :ref:`logging-basic-tutorial`), None to skip initializing
        logging module)
    :param n_module:
        name(s) of network library, first available will be used
        (default: ['enet', 'socket'])
    :type n_module: string or list of strings
    :param s_module:
        name(s) of serialization library, first available will be used
        (default: ['msgpack', 'json'])
    :type s_module: string or list of strings
    :return: True if initialization ended with success

    .. note::
        Because of the dynamic loading of network library adapter,
        :class:`Client` and :class:`Server` classes will only be
        available after initialization.
    """
    global _network_module, _serialization_module
    if logging_lvl is not None:
        logging.basicConfig(level=logging_lvl,
                            format='%(asctime)-8s %(levelname)-8s %(message)s',
                            datefmt='%H:%M:%S')
    network.select_adapter(n_module)
    if network.selected_adapter is not None:
        _logger.info("Using %s",
                     network.selected_adapter.__name__.split('.')[-1])
    else:
        _logger.critical("Can't find any network module")
        return False
    serialization.select_adapter(s_module)
    if serialization.selected_adapter is not None:
        _logger.info("Using %s",
                     serialization.selected_adapter.__name__.split('.')[-1])
    else:
        _logger.critical("Can't find any serialization module")
        return False
    if events:
        _logger.info("Enabling pygame events")
        import event
        event.init(event_val)
    return True
Esempio n. 14
0
def test_event_dual():
    result.clear()

    expected = [('stub1', ('first', )), ('stub1', ('second', ))]

    event.init()
    event.regist('a', stub1)
    event.put('a', ('first', ))
    event.put('a', ('second', ))
    event.exec()
    event.exec()

    assert result == expected
Esempio n. 15
0
def init(events=False, event_val=1, logging_lvl=logging.INFO,
         n_module=('enet', 'socket'), s_module=('msgpack', 'json')):
    """Initialize network library.

    :param events: allow sending Pygame events (default False)
    :param event_val:
        set :const:`event.NETWORK` as
        :const:`pygame.USEREVENT` + :attr:`event_val` (default: 1)
    :param logging_lvl:
        level of logging messages (default :const:`logging.INFO`
        (see: :ref:`logging-basic-tutorial`), None to skip initializing
        logging module)
    :param n_module:
        name(s) of network library, first available will be used
        (default: ['enet', 'socket'])
    :type n_module: string or list of strings
    :param s_module:
        name(s) of serialization library, first available will be used
        (default: ['msgpack', 'json'])
    :type s_module: string or list of strings
    :return: True if initialization ended with success

    .. note::
        Because of the dynamic loading of network library adapter,
        :class:`Client` and :class:`Server` classes will only be
        available after initialization.
    """
    global _network_module, _serialization_module
    if logging_lvl is not None:
        logging.basicConfig(level=logging_lvl,
                            format='%(asctime)-8s %(levelname)-8s %(message)s',
                            datefmt='%H:%M:%S')
    network.select_adapter(n_module)
    if network.selected_adapter is not None:
        _logger.info("Using %s",
            network.selected_adapter.__name__.split('.')[-1])
    else:
        _logger.critical("Can't find any network module")
        return False
    serialization.select_adapter(s_module)
    if serialization.selected_adapter is not None:
        _logger.info("Using %s",
            serialization.selected_adapter.__name__.split('.')[-1])
    else:
        _logger.critical("Can't find any serialization module")
        return False
    if events:
        _logger.info("Enabling pygame events")
        import event
        event.init(event_val)
    return True
Esempio n. 16
0
    def __init__(self):
        super(Hub, self).__init__()
        event.init()

        self.signal_exc_info = None
        self.signal(
            2, lambda signalnum, frame: self.greenlet.parent.throw(
                KeyboardInterrupt))
        self.events_to_add = []

        warnings.warn(
            "ACTION REQUIRED eventlet pyevent hub is deprecated and will be removed soon",
            DeprecationWarning,
        )
Esempio n. 17
0
def main():
    op = optparse.OptionParser(usage='%prog [OPTIONS] [URL|channel]')
    op.add_option('-q',
                  dest='quiet',
                  help='enable quiet output',
                  action='store_true')
    op.add_option('-s',
                  dest='sender',
                  default='*',
                  help='subscribe to messages from this sender')
    op.add_option('-t',
                  dest='type',
                  default='*',
                  help='subscribe to messages of this type')
    opts, args = op.parse_args(sys.argv[1:])
    if not args:
        url = 'http://localhost:8888/msgbus/'
        channel = ''
    elif args[0].startswith('http'):
        url = args[0]
        channel = url.split('/')[-1]
    else:
        url = 'http://localhost:8888/msgbus/%s' % args[0]
        channel = args[0]

    scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
    if not path.startswith('/msgbus/'):
        raise ValueError, 'invalid msgbus URL: %s' % url
    channel = path[8:]
    username, password, hostname, port = parse_netloc(scheme, netloc)

    d = {'quiet': opts.quiet, 'cnt': 0}
    start = time.time()

    event.init()

    evmsg.open(hostname, port, scheme == 'https')
    if username and password:
        evmsg.set_auth(username, password)
    sub = evmsg.subscribe(channel, opts.type, opts.sender, recv_msg, d)

    event.signal(2, event.abort)

    print >> sys.stderr, 'subscribed to', url
    event.dispatch()

    secs = time.time() - start
    print >>sys.stderr, 'received %d msgs over %d secs (%.1f mps)' % \
          (d['cnt'], secs, float(d['cnt']) / secs)
Esempio n. 18
0
		def __init__(self, iface):
			if sys.platform in ('darwin', 'win32'):
				os.putenv('EVENT_NOKQUEUE', '1')
				os.putenv('EVENT_NOPOLL', '1')

			dsniff.config['pcap'] = {}
			dsniff.config['pcap']['interfaces'] = [iface]

			if not self.subclasses:
				subclasses = dsniff.find_subclasses(dsniff.Handler, __import__('dsniffp'))
				if not subclasses:
					raise RuntimeError, 'no Handler subclasses found'

			event.init() # ordering of this matters

			self.handler = pmdsniffh()
			self.handler.setup()
Esempio n. 19
0
def main(argv):
    # initialize libevent
    event.init()

    # set the SIGINT handler
    event.signal(signal.SIGINT, _sigint)

    # create an incoming (listen) socket, and bind
    listen_sock = socket.socket()
    listen_sock.setblocking(0)
    listen_sock.bind(("localhost", listen_port))

    # start listening, set event
    listen_sock.listen(20)
    event.event(listen_read, None, event.EV_READ | event.EV_PERSIST, listen_sock).add()

    # start event loop
    event.dispatch()
Esempio n. 20
0
        def __init__(self, iface):
            if sys.platform in ('darwin', 'win32'):
                os.putenv('EVENT_NOKQUEUE', '1')
                os.putenv('EVENT_NOPOLL', '1')

            dsniff.config['pcap'] = {}
            dsniff.config['pcap']['interfaces'] = [iface]

            if not self.subclasses:
                subclasses = dsniff.find_subclasses(dsniff.Handler,
                                                    __import__('dsniffp'))
                if not subclasses:
                    raise RuntimeError, 'no Handler subclasses found'

            event.init()  # ordering of this matters

            self.handler = pmdsniffh()
            self.handler.setup()
Esempio n. 21
0
def main():
    op = optparse.OptionParser(usage='%prog [OPTIONS] [URL|channel]')
    op.add_option('-q', dest='quiet', help='enable quiet output',
                  action='store_true')
    op.add_option('-s', dest='sender', default='*',
                  help='subscribe to messages from this sender')
    op.add_option('-t', dest='type', default='*',
                  help='subscribe to messages of this type')
    opts, args = op.parse_args(sys.argv[1:])
    if not args:
        url = 'http://localhost:8888/msgbus/'
        channel = ''
    elif args[0].startswith('http'):
        url = args[0]
        channel = url.split('/')[-1]
    else:
        url = 'http://localhost:8888/msgbus/%s' % args[0]
        channel = args[0]
        
    scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
    if not path.startswith('/msgbus/'):
        raise ValueError, 'invalid msgbus URL: %s' % url
    channel = path[8:]
    username, password, hostname, port = parse_netloc(scheme, netloc)
    
    d = { 'quiet':opts.quiet, 'cnt':0 }
    start = time.time()
    
    event.init()

    evmsg.open(hostname, port, scheme == 'https')
    if username and password:
        evmsg.set_auth(username, password)
    sub = evmsg.subscribe(channel, opts.type, opts.sender, recv_msg, d)
    
    event.signal(2, event.abort)
    
    print >>sys.stderr, 'subscribed to', url
    event.dispatch()

    secs = time.time() - start
    print >>sys.stderr, 'received %d msgs over %d secs (%.1f mps)' % \
          (d['cnt'], secs, float(d['cnt']) / secs)
Esempio n. 22
0
 def __init__(self):
     asyncore.dispatcher.__init__(self)
     self.logpath = os.path.join(world.logDir, 'server')
     self.events = []
     # Uncomment the below line if you want IPV6, or if your host operating system
     # allows mapped IPV4->IPV6 nativly.  Windows 7 doesn't do this (probably
     # without some flag I'm not setting....... I know Linux works.
     # self.create_socket(AF_INET6, SOCK_STREAM)
     self.create_socket(AF_INET, SOCK_STREAM)
     self.set_reuse_addr()
     self.bind(('', 4000))
     self.listen(5)
     helpsys.init()
     races.init()
     commands.init()
     event.init()
     area.init()
     event.init_events_server(self)
     print('APM is up and running in {0:,.3f} seconds.'.format(time.time() - startup))
Esempio n. 23
0
def load_save_from_path(path, keep_config=False, keep_velocity=False):
    global player, current_level
    reset()
    event.init()
    stream = file(path, 'r')
    yaml_objects = [obj for obj in yaml.load(stream) if obj != None]
    stream.close()
    
    level_module = None
    
    target_queue = []
    
    if player != None:
        for unit in player.units:
            unit.batch = None
    
    for obj in yaml_objects:
        try:
            getattr(saveloaders, obj.yaml_tag[3:])(obj)
        except:
            if obj.yaml_tag == u"!i_LevelData":
                change_level_set(obj.level_dir)
                current_level = obj.level_name
                savegame.set_current_level(obj.level_dir, current_level)
                level_module = __import__(current_level)
                path = os.path.join(level_dir, obj.level_name+".yaml")
                stream = file(path, 'r')
                yaml_geometry = yaml.load(stream)
                stream.close()
                load_geometry(yaml_geometry)
            elif obj.yaml_tag == u"!i_GlueBody":
                if not obj.is_player or not keep_config:
                    unit_list = [saveloaders.unit_from_dict(u) for u in obj.units]
                    new_gluebody = body.GlueBody(
                        obj.position, obj.angle, unit_list
                    )
                    new_gluebody.attachable = obj.attachable
                    new_gluebody.body.velocity = obj.velocity
                    new_gluebody.body.angular_velocity = obj.angular_velocity
                    if obj.is_player:
                        player = new_gluebody
                    for unit in unit_list:
                        if hasattr(unit, 'update_patients_now'):
                            unit.update_patients_now = True
                    
                if obj.is_player and keep_config:
                    player.body.position = obj.position
                    if not keep_velocity:
                        player.body.velocity.x = 0.0
                        player.body.velocity.y = 0.0
                    physics.body_update_list.append(player)
                    physics.unit_update_list.extend(player.units)
                    physics.space.add(player.body)
                    for unit in player.units:
                        unit.add_shapes()
                        unit.batch = batch
                        unit.migrate()
                        if unit.using_sound: unit.init_sound(unit.sound, unit.loop_sound)
            elif obj.yaml_tag == u"!i_Turret":
                new_turret = saveloaders.make_turret(obj)
                new_turret.active = obj.active
                target_queue.append((new_turret, obj.target))
                if not obj.visible: new_turret.make_invisible()
            else:
                print "Did not load", obj
    
    for obj, target in target_queue:
        if target > 0:
            obj.target = event.get_object(target)
    event.update_player_units(player.units)
    resources.wall_sound = resources.metal_against_metal2
    if hasattr(level_module, 'on_load'):
        level_module.on_load()
Esempio n. 24
0
 def __enter__(self):
     event.init()
Esempio n. 25
0
 def setUp(self):
     event.init()
Esempio n. 26
0
 def setUp(self):
     event.init()
Esempio n. 27
0
                                for method in addon()._old_owners_methods: self._owner.__dict__[method.__name__]=method
                            del self._owner.__dict__[addon().__class__.__name__]
                            if 'plugout' in addon().__class__.__dict__: addon().plugout()
                        if addon().__class__.__name__ in self._owner.__dict__:
                            self._owner.DEBUG('server','Error: Could not un-plug %s'%addon().__class__.__name__,'error')
                        self._owner.unfeature(addon.NS)

            elif the_input == 'quit':
                GLOBAL_TERMINATE = True
                event.abort()
                break
            time.sleep(.01)

cmd_options.enable_debug=True
if __name__=='__main__':
    if 'event' in globals().keys(): event.init()
    debug_mode = None
    debug_file = sys.stdout
    if globals()['cmd_options'].enable_debug:
        debug_mode = ['always']
    else:
        debug_file = open('xmppd.log','w+')
    s=Server(debug_mode,False,debug_file)
#    import pdb;pdb.set_trace()
    inpt_service = get_input(s)
    inpt_service.setDaemon(True)

    GLOBAL_TERMINATE = False
    if cmd_options.enable_interactive: inpt_service.start()
    while GLOBAL_TERMINATE == False:
        try:
Esempio n. 28
0
    if FIX_ERROR:
        CONN.delete(MRJ['jid'], result_callback=got_response,
            result_callback_args = (CONN,))
        return
    print 'aborting now'
    event.abort()

def start(conn):
    print 'start called'
    conn.reserve()
    return

def main():
    global CONN
    # setup the connection
    myconn = beanstalk.serverconn.LibeventConn(SERVER, PORT)
    #setup callbacks
    myconn.result_callback_args = (myconn,)
    myconn.result_callback = got_response
    myconn.error_callback = got_error

    #setup the callchain
    start(myconn)
    CONN = myconn
    print 'dispatching'
    event.dispatch()

if __name__ == '__main__':
    event.init()
    main()