Python asyncio 模块,ensure_future() 实例源码

我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用asyncio.ensure_future()

项目:python-libjuju    作者:juju    | 项目源码 | 文件源码
def _notify_observers(self, delta, old_obj, new_obj):
        """Call observing callbacks, notifying them of a change in model state

        :param delta: The raw change from the watcher
            (:class:`juju.client.overrides.Delta`)
        :param old_obj: The object in the model that this delta updates.
            May be None.
        :param new_obj: The object in the model that is created or updated
            by applying this delta.

        """
        if new_obj and not old_obj:
            delta.type = 'add'

        log.debug(
            'Model changed: %s %s %s',
            delta.entity, delta.type, delta.get_id())

        for o in self._observers:
            if o.cares_about(delta):
                asyncio.ensure_future(o(delta, old_obj, new_obj, self),
                                      loop=self._connector.loop)
项目:pyppeteer    作者:miyakogi    | 项目源码 | 文件源码
def waitFor(self, selectorOrFunctionOrTimeout: Union[str, int, float],
                options: dict = None, **kwargs: Any) -> Awaitable:
        """Wait until `selectorOrFunctionOrTimeout`."""
        if options is None:
            options = dict()
        options.update(kwargs)
        if isinstance(selectorOrFunctionOrTimeout, (int, float)):
            fut: Awaitable[None] = asyncio.ensure_future(
                asyncio.sleep(selectorOrFunctionOrTimeout))
            return fut
        if not isinstance(selectorOrFunctionOrTimeout, str):
            fut = asyncio.get_event_loop().create_future()
            fut.set_exception(TypeError(
                'Unsupported target type: ' +
                str(type(selectorOrFunctionOrTimeout))
            ))
            return fut
        if ('=>' in selectorOrFunctionOrTimeout or
                selectorOrFunctionOrTimeout.strip().startswith('function')):
            return self.waitForFunction(selectorOrFunctionOrTimeout, options)
        return self.waitForSelector(selectorOrFunctionOrTimeout, options)
项目:kas    作者:siemens    | 项目源码 | 文件源码
def repos_fetch(config, repos):
    """
        Fetches the list of repositories to the kas_work_dir.
    """
    tasks = []
    for repo in repos:
        if not hasattr(asyncio, 'ensure_future'):
            # pylint: disable=no-member,deprecated-method
            task = asyncio.async(_repo_fetch_async(config, repo))
        else:
            task = asyncio.ensure_future(_repo_fetch_async(config, repo))
        tasks.append(task)

    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.wait(tasks))

    for task in tasks:
        if task.result():
            sys.exit(task.result())
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def destroy_sync(self):
        """
        Destroy the Manialink with it's handlers and references.
        Will also hide the Manialink for all users!

        This method is sync and will call a async method (destroying of the manialink at our players) async but will not
        be executed at the same time. Be aware with this one!
        """
        try:
            SignalManager.get_signal('maniaplanet:manialink_answer').unregister(self.handle)
            asyncio.ensure_future(self.manager.destroy(self))
        except Exception as e:
            logging.exception(e)
        self.receivers = dict()
        self.data = None
        self.player_data = None
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def create_vote(self, action, player, finished_event):
        new_vote = Vote()
        new_vote.action = action
        new_vote.requester = player
        new_vote.votes_current = []
        needed_votes = math.ceil(self.instance.player_manager.count_players / 2)
        if needed_votes == math.floor(self.instance.player_manager.count_players / 2):
            needed_votes += 1
        if needed_votes > self.instance.player_manager.count_players:
            needed_votes = self.instance.player_manager.count_players
        new_vote.votes_required = needed_votes
        new_vote.vote_added = self.vote_added
        new_vote.vote_removed = self.vote_removed
        new_vote.vote_finished = finished_event

        asyncio.ensure_future(self.vote_reminder(new_vote))

        return new_vote
项目:pyppeteer    作者:miyakogi    | 项目源码 | 文件源码
def __init__(self, url: str, delay: int = 0) -> None:
        """Make connection.

        :arg str url: WebSocket url to connect devtool.
        :arg int delay: delay to wait until send messages.
        """
        super().__init__()
        self._url = url
        self._lastId = 0
        self._callbacks: Dict[int, asyncio.Future] = dict()
        self._delay = delay
        self._sessions: Dict[str, Session] = dict()
        self.connection: Session
        self._connected = False
        self._ws = websockets.client.connect(self._url)
        self._recv_fut = asyncio.ensure_future(self._recv_loop())
项目:aiosubdomainBrute    作者:OOsec    | 项目源码 | 文件源码
def run(self):
        size = self.queue.qsize()
        print('[*] qsize: {}'.format(size))
        print('[*] test_wildcard_dns_record')
        self.test_wildcard_dns_record()

        for i in range(size):
            task = asyncio.ensure_future(self.dns_query())
            self.tasks.append(task)
        try:
            responses = asyncio.gather(*self.tasks)
            result = self.loop.run_until_complete(responses)
            result = list(filter(lambda r:r is not None, result))
            print('[+] Found {} subdomain'.format(len(result)))
        except Exception as e:
            print(e)
项目:aiosubdomainBrute    作者:OOsec    | 项目源码 | 文件源码
def test_wildcard_dns_record(self):
        global wildcard_dns_record
        ip_dic = {}
        genrandstr = lambda i: ''.join(random.choices(string.ascii_lowercase + string.digits, k=i))
        tasks = [asyncio.ensure_future(self.resolver.query(genrandstr(20) + '.' + self.domain, 'A')) for _ in range(6)]
        reqs = asyncio.gather(*tasks)
        result = self.loop.run_until_complete(reqs)
        for r in result:
            if ip_dic.get(r.ip[0]):
                ip_dic[r.ip[0]] += 1
                if ip_dic[r.ip[0]] > 3:
                    wildcard_dns_record = r.ip[0]
                    print(f'[*] Found wildcard dns record:{wildcard_dns_record}')
                    return
            else:
                ip_dic[r.ip[0]] = 1
项目:uzdevsbot    作者:Uzbek-Developers    | 项目源码 | 文件源码
def _process_update(self, update):
        logger.debug("update %s", update)

        # Update offset
        self._offset = max(self._offset, update["update_id"])

        coro = None

        # Determine update type starting with message updates
        for ut in MESSAGE_UPDATES:
            if ut in update:
                coro = self._process_message(update[ut])
                break
        else:
            if "inline_query" in update:
                coro = self._process_inline_query(update["inline_query"])
            elif "callback_query" in update:
                coro = self._process_callback_query(update["callback_query"])

        if coro:
            asyncio.ensure_future(coro)
项目:socketshark    作者:closeio    | 项目源码 | 文件源码
def ping_handler(self):
        ping_interval = self.shark.config['WS_PING']['interval']
        if not ping_interval:
            return
        latency = 0
        while True:
            await asyncio.sleep(ping_interval - latency)
            self.session.log.debug('ping')
            start_time = time.time()
            try:
                ping = await self.websocket.ping()
            except websockets.ConnectionClosed:
                return
            timeout_handler = asyncio.ensure_future(
                    self.ping_timeout_handler(ping))
            await ping
            latency = time.time() - start_time
            self.session.log.debug('pong', latency=round(latency, 3))
            # Return immediately if a ping timeout occurred.
            if not timeout_handler.cancel() and timeout_handler.result():
                return
项目:socketshark    作者:closeio    | 项目源码 | 文件源码
def consumer_handler(self):
        try:
            ping_handler = asyncio.ensure_future(self.ping_handler())
            try:
                while True:
                    event = await self.websocket.recv()
                    try:
                        data = json.loads(event)
                    except json.decoder.JSONDecodeError:
                        self.session.log.warn('received invalid json')
                        await self.send({
                            "status": "error",
                            "error": c.ERR_INVALID_EVENT,
                        })
                    else:
                        await self.session.on_client_event(data)
            except websockets.ConnectionClosed:
                await self.session.on_close()

            ping_handler.cancel()
        except Exception:
            self.session.log.exception('unhandled error in consumer handler')
项目:aio-service-client    作者:alfred82santa    | 项目源码 | 文件源码
def test_limit(self):
        await self.plugin.before_request(self.endpoint_desc, self.session,
                                         self.request_params)

        fut = asyncio.ensure_future(self.plugin.before_request(self.endpoint_desc, self.session,
                                                               self.request_params))

        with self.assertRaises(TimeoutError):
            await asyncio.wait_for(shield(fut), 0.1)

        await self.plugin.on_response(self.endpoint_desc, self.session,
                                      self.request_params, None)

        await asyncio.sleep(0.2)

        await asyncio.wait_for(fut, 0.5)
项目:uchroma    作者:cyanogen    | 项目源码 | 文件源码
def ensure_future(coro, loop=None):
    """
    Wrapper for asyncio.ensure_future which dumps exceptions
    """
    if loop is None:
        loop = asyncio.get_event_loop()
    fut = asyncio.ensure_future(coro, loop=loop)
    def exception_logging_done_cb(fut):
        try:
            e = fut.exception()
        except asyncio.CancelledError:
            return
        if e is not None:
            loop.call_exception_handler({
                'message': 'Unhandled exception in async future',
                'future': fut,
                'exception': e,
            })
    fut.add_done_callback(exception_logging_done_cb)
    return fut
项目:uchroma    作者:cyanogen    | 项目源码 | 文件源码
def animate(self, start: float, end: float, done_cb=None):
        """
        Executes the given callback over the period of max_time
        at the given FPS, to animate from start to end.
        This can be used for things like brightness levels.

        :param start: Starting value
        :param end: Ending value
        """
        if asyncio.get_event_loop().is_running():
            if self._task is not None:
                self._task.cancel()
            self._task = ensure_future(self._animate(start, end))
            if done_cb is not None:
                self._task.add_done_callback(done_cb)
        else:
            self._callback(end)
项目:oshino    作者:CodersOfTheNight    | 项目源码 | 文件源码
def flush(client, transport, logger):
    future = asyncio.Future()

    async def process_async(future):
        try:
            transport.connect()
            client.flush()
            transport.disconnect()

            future.set_result(True)
        except ConnectionRefusedError as ce:
            logger.warn(ce)

            future.set_result(False)

    asyncio.ensure_future(process_async(future))
    await future
    return future.result()
项目:aiotasks    作者:cr0hn    | 项目源码 | 文件源码
def stop(self):
        self.stop_delayers()
        self.stop_subscriptions()

        for t in asyncio.Task.all_tasks(loop=self._loop_subscribers):
            t.cancel()
        for t in asyncio.Task.all_tasks(loop=self._loop_delay):
            t.cancel()

        # Ensure all the tasks ends
        async def close_delay_loop():
            self._loop_delay.stop()

        async def close_subscribers_loop():
            self._loop_subscribers.stop()

        self.loop.run_until_complete(asyncio.ensure_future(
            close_delay_loop()))
        self.loop.run_until_complete(asyncio.ensure_future(
            close_subscribers_loop()))
项目:snakepit-game    作者:7WebPages    | 项目源码 | 文件源码
def wshandler(request):
    app = request.app
    ws = web.WebSocketResponse()
    await ws.prepare(request)
    app["sockets"].append(ws)

    if app["game_is_running"] == False:
        asyncio.ensure_future(game_loop(app))
    while 1:
        msg = await ws.receive()
        if msg.tp == web.MsgType.text:
            print("Got message %s" % msg.data)
            ws.send_str("Pressed key code: {}".format(msg.data))
        elif msg.tp == web.MsgType.close or\
             msg.tp == web.MsgType.error:
            break

    app["sockets"].remove(ws)
    print("Closed connection")

    return ws
项目:irisett    作者:beebyte    | 项目源码 | 文件源码
def running(self, event_name: str, **kwargs: Any) -> None:
        """An event is running.

        Listener callbacks will be called with:
        callback(listener-dict, event-name, timestamp, arg-dict)
        """
        stats.inc('events_fired', 'EVENT')
        if not self.listeners:
            return
        timestamp = time.time()
        for listener in self.listeners:
            if not listener.wants_event(event_name, kwargs):
                continue
            try:
                t = listener.callback(listener, event_name, timestamp, kwargs)
                asyncio.ensure_future(t)
            except Exception as e:
                log.msg('Failed to run event listener callback: %s' % str(e))
项目:irisett    作者:beebyte    | 项目源码 | 文件源码
def notify_state_change(self, prev_state: str, prev_state_ts: float) -> None:
        if not self.alerts_enabled:
            self.log_debug('skipping alert notifications, disabled')
            return
        contacts = await contact.get_contact_dict_for_active_monitor(
            self.manager.dbcon, self.id)
        metadata = await self.get_metadata()
        tmpl_data = {}  # type: Dict[str, Any]
        for key, value in metadata.items():
            tmpl_data['meta_%s' % key] = value
        if prev_state_ts and self.state_ts - prev_state_ts:
            tmpl_data['state_elapsed'] = utils.get_display_time(self.state_ts - prev_state_ts)
        tmpl_data['state'] = self.state
        tmpl_data['prev_state'] = prev_state
        tmpl_data['type'] = 'active_monitor'
        tmpl_data['id'] = self.id
        tmpl_data['monitor_description'] = self.get_description()
        tmpl_data['msg'] = self.msg
        # Don't wait for notifications to be sent, it may or may not take a
        # while and we don't want to pause the monitoring to wait for it.
        asyncio.ensure_future(
            self.manager.notification_manager.send_notification(contacts, tmpl_data))
项目:bottery    作者:rougeth    | 项目源码 | 文件源码
def polling(self, last_update=None):
        payload = {}
        if last_update:
            # `offset` param prevets from getting duplicates updates
            # from Telegram API:
            # https://core.telegram.org/bots/api#getupdates
            payload['offset'] = last_update + 1

        updates = await self.api.get_updates(**payload)

        # If polling request returned at least one update, use its ID
        # to define the offset.
        if len(updates.get('result', [])):
            last_update = updates['result'][-1]['update_id']

        # Handle each new message, send its responses and then request
        # updates again.
        tasks = [self.message_handler(msg) for msg in updates['result']]
        await asyncio.gather(*tasks)
        asyncio.ensure_future(self.polling(last_update))
项目:globibot    作者:best-coloc-ever    | 项目源码 | 文件源码
def _send(self, method, *args, **kwargs):
        try:
            content = kwargs['content']
            kwargs['content'] = f.truncated_content(content)
        except KeyError:
            pass

        delete_after = kwargs.pop('delete_after', None)

        try:
            message = await method(*args, **kwargs)
        except Exception as e:
            self.error('{} failed: {}'.format(method.__name__, e))
            return None

        if delete_after:
            future = self.delete_message_after(message, delete_after)
            asyncio.ensure_future(future)

        return message
项目:globibot    作者:best-coloc-ever    | 项目源码 | 文件源码
def run_async(self, command, directory, image, user_id):
        if user_id not in self.user_volumes:
            self.create_volume_for(user_id)

        volume = volume_name(user_id)
        host_config = self.create_host_config(binds = {
            directory: dict(bind=WORK_DIR),
            volume: dict(bind=PERSISTENT_DATA_DIR)
        })
        host_config['PidsLimit'] = PID_LIMIT

        container = self.create_container(
            volumes     = [WORK_DIR, PERSISTENT_DATA_DIR],
            image       = image,
            working_dir = WORK_DIR,
            host_config = host_config,
            command     = command
        )
        self.start(container)

        iterator = AsyncIterator()
        executor = iterator.start(self.logs, container, stream=True)
        asyncio.ensure_future(self.poll_container(container, executor))

        return iterator
项目:PomodoroBot    作者:VicenteRD    | 项目源码 | 文件源码
def safe_send(self, dest, content: str, **kwargs):
        """ Sends a message and then deletes it after a certain time has passed.

        :param dest: Where the message will be sent.
        :param content: The content of the message to send.
        """
        tts = kwargs.pop('tts', False)
        delete_after = kwargs.pop('delete_after', 0)

        message = await self.send_message(
            lib.as_object(dest) if isinstance(dest, str) else dest,
            content, tts=tts)

        if message and delete_after > 0:
            @asyncio.coroutine
            def delete():
                yield from asyncio.sleep(delete_after)
                yield from self.delete_message(message)

            asyncio.ensure_future(delete(), loop=self.loop)
项目:adbus    作者:ccxtechnologies    | 项目源码 | 文件源码
def defer_property_updates(self, enable):
        if enable:
            self._defer_properties = True

        elif self._defer_properties:
            if not self.service.is_running():
                return

            self._defer_properties = False
            if self._deferred_property_signals:
                asyncio.ensure_future(
                        self.sdbus.emit_properties_changed(
                                list(self._deferred_property_signals.keys())
                        ),
                        loop=self.service.get_loop()
                )

                self._deferred_property_signals = {}
项目:tukio    作者:optiflows    | 项目源码 | 文件源码
def new_task(task_name, *, data=None, config=None, timeout=None, loop=None):
    """
    Schedules the execution of the coroutine registered as `task_name` (either
    defined in a task holder class or not) in the loop and returns an instance
    of `asyncio.Task()` (or a subclass of it).
    """
    klass, coro_fn = TaskRegistry.get(task_name)
    if klass:
        task_holder = klass(config)
        coro = coro_fn(task_holder, data)
    else:
        coro = coro_fn(data)

    task = asyncio.ensure_future(coro, loop=loop)
    if timeout:
        TimeoutHandle(task, timeout).start()
    return task
项目:mockaioredis    作者:kblin    | 项目源码 | 文件源码
def __init__(self, address, db=0, password=0, encoding=None,
                 *, minsize, maxsize, commands_factory, ssl=None, loop=None):
        if loop is None:
            loop = asyncio.get_event_loop()

        self._address = address
        self._db = db
        self._password = password
        self._encoding = encoding
        self._minsize = minsize
        self._maxsize = maxsize
        self._factory = commands_factory
        self._ssl = ssl
        self._loop = loop

        # fake it here, we always only have one connection
        self._pool = collections.deque(maxlen=1)
        self._used = set()
        self._acquiring = 0

        self._cond = asyncio.Condition(loop=loop)
        self._close_state = asyncio.Event(loop=loop)
        self._close_waiter = asyncio.ensure_future(self._do_close(), loop=loop)
项目:monopoly-open-bid    作者:Rosuav    | 项目源码 | 文件源码
def __init__(self, id):
        if os.environ.get("WS_KEEPALIVE"):
            asyncio.ensure_future(self.keepalive())
        self.clients = []
        self.proporder = []
        self.funds = 1500 # Everyone's initial spendable money
        self.id = id; rooms[self.id] = self # floop
        print("Creating new room %s [%d rooms]" % (self.id, len(rooms)))
        self.dying = None # Set to true when we run out of clients
        self.all_done = False

        # Preprocess the property data into a more useful form.
        self.properties = {}
        for group in self.property_data.splitlines():
            group = group.strip()
            if not group: continue
            color, price1, price2, names = re.match("([A-Za-z/]+): ([0-9]+)/([0-9]+) (.*)", group).groups()
            names = names.split(", ")
            if "/" in color: color, fg = color.split("/")
            else: fg = "Black"
            for name in names:
                self.proporder.append(name)
                self.properties[name] = {"facevalue": int(price1), "color": color, "fg": fg}
            # Alter the price of the last one (the top one of the group)
            self.properties[name]["facevalue"] = int(price2)
项目:aiossdb    作者:Microndgt    | 项目源码 | 文件源码
def __init__(self, reader, writer, *, address, encoding=None, parser=None, loop=None):
        if loop is None:
            # ????asyncio?????
            loop = asyncio.get_event_loop()
        if parser is None:
            parser = SSDBParser
        assert callable(parser), "Parser argument: {} is not callable".format(parser)
        self._reader = reader
        self._writer = writer
        self._address = address
        self._loop = loop
        # ???????????????????????popleft
        self._waiters = deque()
        self._parser = parser(encoding=encoding)
        # ?????task, self._read_data()????????????????????
        # ensure_future ??????????????????Future???????????????Task??
        self._reader_task = asyncio.ensure_future(self._read_data(), loop=self._loop)
        # ??????????????????????????????????)
        self._close_waiter = asyncio.Future(loop=self._loop)
        # ?????????(?????)?????
        self._reader_task.add_done_callback(self._close_waiter.set_result)
        self._encoding = encoding

        self._closing = False
        self._closed = False
项目:aiossdb    作者:Microndgt    | 项目源码 | 文件源码
def release(self, conn):
        """?????????used???????pool??????????????
        ????????????????????????????"""
        # ?????????pool?used?
        if self.closed:
            raise PoolClosedError("Pool is closed")
        assert conn in self._used, ("Invalid connection, maybe from other pool", conn)
        self._used.remove(conn)
        # ?????????????????
        if not conn.closed:
            self._pool.append(conn)
        else:
            # ???????????
            logger.warn("Connection {} has been closed".format(conn))

        # ??????????
        asyncio.ensure_future(self._wake_up(), loop=self._loop)
项目:Auspex    作者:BBN-Q    | 项目源码 | 文件源码
def receive_data(self, channel, oc):
        # push data from a socket into an OutputConnector (oc)
        self.last_timestamp = datetime.datetime.now()
        # wire format is just: [size, buffer...]
        sock = self._chan_to_rsocket[channel]
        # TODO receive 4 or 8 bytes depending on sizeof(size_t)
        msg = sock.recv(8)
        # reinterpret as int (size_t)
        msg_size = struct.unpack('n', msg)[0]
        buf = sock.recv(msg_size, socket.MSG_WAITALL)
        if len(buf) != msg_size:
            logger.error("Channel %s socket msg shorter than expected" % channel.channel)
            logger.error("Expected %s bytes, received %s bytes" % (msg_size, len(buf)))
            # assume that we cannot recover, so stop listening.
            loop = asyncio.get_event_loop()
            loop.remove_reader(sock)
            return
        data = np.frombuffer(buf, dtype=channel.dtype)
        asyncio.ensure_future(oc.push(data))
项目:Auspex    作者:BBN-Q    | 项目源码 | 文件源码
def receive_data(self, channel, oc):
        # push data from a socket into an OutputConnector (oc)
        self.last_timestamp = datetime.datetime.now()
        self.fetch_count += 1
        # wire format is just: [size, buffer...]
        sock = self._chan_to_rsocket[channel]
        # TODO receive 4 or 8 bytes depending on sizeof(size_t)
        msg = sock.recv(8)
        # reinterpret as int (size_t)
        msg_size = struct.unpack('n', msg)[0]
        buf = sock.recv(msg_size, socket.MSG_WAITALL)
        if len(buf) != msg_size:
            logger.error("Channel %s socket msg shorter than expected" % channel.channel)
            logger.error("Expected %s bytes, received %s bytes" % (msg_size, len(buf)))
            # assume that we cannot recover, so stop listening.
            loop = asyncio.get_event_loop()
            loop.remove_reader(sock)
            return
        data = np.frombuffer(buf, dtype=np.float32)
        asyncio.ensure_future(oc.push(data))
项目:pytwitcher    作者:adongy    | 项目源码 | 文件源码
def __init__(self, loop: asyncio.BaseEventLoop = None, **config):
        if loop is None:
            try:
                loop = asyncio.get_event_loop()
            except RuntimeError:
                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(loop)

        # TOOD: say in the docs that we take ownership of the loop, we close it
        # ourselves in run()
        self.loop = loop
        self.config = dict(self.DEFAULTS, **config)

        self.encoding = self.config['encoding']
        self.registry = registry.Registry(self.config)
        self.queue = asyncio.Queue(loop=self.loop)

        asyncio.ensure_future(self._process_queue(), loop=self.loop)
项目:scriptworker    作者:mozilla-releng    | 项目源码 | 文件源码
def test_raise_future_exceptions(event_loop, exc):

    async def one():
        if exc is not None:
            raise exc("foo")

    async def two():
        pass

    tasks = [asyncio.ensure_future(one()), asyncio.ensure_future(two())]
    if exc is not None:
        with pytest.raises(exc):
            event_loop.run_until_complete(
                utils.raise_future_exceptions(tasks)
            )
    else:
        event_loop.run_until_complete(
            utils.raise_future_exceptions(tasks)
        )
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def print_footer(self):  # pragma: no cover
        await self.chat(
            '\uf1e6 $o$FD4Py$369Planet$z$o$s$fff v{}, {}\uf013 $z$s $369|$FD4 '
            '$l[http://pypla.net]Site$l $369|$FD4 '
            '$l[https://github.com/PyPlanet]Github$l $369|$FD4 '
            '$l[http://pypla.net]Docs$l'.format(version, len(self.apps.apps)),
            raw=True
        )

        try:
            asyncio.ensure_future(releases.UpdateChecker.init_checker(self))
        except:
            pass  # Completely ignore errors while checking for the latest version.
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def on_start(self):
        asyncio.ensure_future(self.send_loop())
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def performance_mode(self, new_value):
        if self._performance_mode != new_value:
            if new_value:
                asyncio.ensure_future(
                    pyplanet_performance_mode_begin.send_robust(source=dict(
                        old_value=self._performance_mode, new_value=new_value
                    ))
                )
            else:
                asyncio.ensure_future(
                    pyplanet_performance_mode_end.send_robust(source=dict(
                        old_value=self._performance_mode, new_value=new_value
                    ))
                )
        self._performance_mode = new_value
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def authenticate(self):
        try:
            result = await self.multicall(
                ('dedimania.OpenSession', {
                    'Game': self.game, 'Login': self.server_login, 'Code': self.dedimania_code, 'Path': self.path,
                    'Packmask': self.pack_mask, 'ServerVersion': self.server_version, 'ServerBuild': self.server_build,
                    'Tool': 'PyPlanet', 'Version': str(version)
                })
            )
        except DedimaniaTransportException as e:
            logger.error('Dedimania Error during authentication: {}'.format(str(e)))
            return
        if not result:
            return

        try:
            if 'Error' in result[0][0] and 'Bad code' in result[0][0]['Error'].lower():
                raise DedimaniaInvalidCredentials('Bad code or login!')
        except DedimaniaInvalidCredentials:
            raise
        except:
            pass

        self.session_id = result[0][0]['SessionId']

        if not self.update_task:
            self.update_task = asyncio.ensure_future(self.update_loop())

        return self.session_id
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def reload_settings(self, *args, **kwargs):
        # Check setting + return errors if not correct!
        self.login = await self.setting_server_login.get_value(refresh=True) or self.instance.game.server_player_login
        self.code = await self.setting_dedimania_code.get_value(refresh=True)
        if not self.code:
            message = '$0b3Error: No dedimania code was provided, please edit the settings (//settings).'
            logger.error('Dedimania Code not configured! Please configure with //settings!')
            await self.instance.chat(message)
            return

        # Save current script name
        self.current_script = await self.instance.mode_manager.get_current_script()

        # Init API (execute this in a non waiting future).
        self.api = DedimaniaAPI(
            self.instance,
            self.login, self.code, self.instance.game.server_path, self.instance.map_manager.current_map.environment,
            self.instance.game.dedicated_version, self.instance.game.dedicated_build
        )
        asyncio.ensure_future(self.initiate_api())
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def on_start(self):
        self.context.signals.listen(tm_signals.waypoint, self.player_cp)
        self.context.signals.listen(mp_signals.player.player_connect, self.player_connect)
        self.context.signals.listen(mp_signals.map.map_begin, self.map_begin)
        self.context.signals.listen(mp_signals.map.map_start__end, self.map_end)
        self.best_cp_times.clear()
        self.widget = BestCpTimesWidget(self)
        asyncio.ensure_future(self.widget.display())

    # When a player passes a CP
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def vote_reminder(self, vote):
        await asyncio.sleep(await self.setting_remind_interval.get_value())

        if self.current_vote is not None:
            required_votes = (self.current_vote.votes_required - len(self.current_vote.votes_current))
            current_required_votes = (vote.votes_required - len(vote.votes_current))
            if self.current_vote.action == vote.action and current_required_votes == required_votes:
                message = '$0cfThere are $fff{}$0cf more {} needed to $fff{}$0cf (use $fffF5$0cf to vote).'.format(
                    current_required_votes, ('votes' if current_required_votes > 1 else 'vote'), self.current_vote.action
                )
                await self.instance.chat(message)

                asyncio.ensure_future(self.vote_reminder(vote))
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def on_after_start(self, *args, **kwargs):
        await asyncio.sleep(1)
        asyncio.ensure_future(asyncio.gather(*[
            self.player_connect(p) for p in self.instance.player_manager.online
        ]))
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def on_chat(self, player, text, cmd, **kwargs):
        if not cmd and self.chat_redirection:
            if player.level > 0:
                asyncio.ensure_future(self.instance.chat(
                    '$z[{}$z$s] {}'.format(player.nickname, text), raw=True
                ))
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def on_after_start(self, *args, **kwargs):
        await asyncio.sleep(1)
        asyncio.ensure_future(asyncio.gather(*[
            self.player_connect(p) for p in self.instance.player_manager.online
        ]))
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def on_start(self):
        self.context.signals.listen(mp_signals.map.map_begin, self.map_begin)
        self.context.signals.listen(mp_signals.player.player_connect, self.player_connect)

        # Move the multilapinfo a bit. (Only Trackmania).
        self.instance.ui_manager.properties.set_attribute('multilap_info', 'pos', '107., 88., 5.')
        self.instance.ui_manager.properties.set_visibility('map_info', False)

        self.map_widget = views.MapInfoWidget(self)

        # Don't wait on the displaying of the widget.
        asyncio.ensure_future(self.map_widget.display())

        await self.output_deprecated()
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def init_checker(self, instance):
        """
        Initiate checker.

        :param instance: Instance of controller.
        :type instance: pyplanet.core.instance.Instance
        """
        self.instance = instance
        self.instance.signals.listen('maniaplanet:player_connect', self.connect)

        asyncio.ensure_future(self.check(True))
        asyncio.ensure_future(self.loop())
项目:PyPlanet    作者:PyPlanet    | 项目源码 | 文件源码
def setUp(self):
        self.instance = Controller.prepare(name='default').instance
        await self.instance._start()
        asyncio.ensure_future(self.instance.gbx.listen())
项目:python-libjuju    作者:juju    | 项目源码 | 文件源码
def add_unit(self, count=1, to=None):
        """Add one or more units to this application.

        :param int count: Number of units to add
        :param str to: Placement directive, e.g.::
            '23' - machine 23
            'lxc:7' - new lxc container on machine 7
            '24/lxc/3' - lxc container 3 or machine 24

            If None, a new machine is provisioned.

        """
        app_facade = client.ApplicationFacade.from_connection(self.connection)

        log.debug(
            'Adding %s unit%s to %s',
            count, '' if count == 1 else 's', self.name)

        result = await app_facade.AddUnits(
            application=self.name,
            placement=parse_placement(to) if to else None,
            num_units=count,
        )

        return await asyncio.gather(*[
            asyncio.ensure_future(self.model._wait_for_new('unit', unit_id))
            for unit_id in result.units
        ])
项目:pyppeteer    作者:miyakogi    | 项目源码 | 文件源码
def stop(self) -> Awaitable:
        """Stop."""
        contentPromise = asyncio.get_event_loop().create_future()
        self._client.once(
            'Tracing.tracingComplete',
            lambda event: asyncio.ensure_future(
                self._readStream(event.get('stream'), self._path)
            ).add_done_callback(
                lambda fut: contentPromise.set_result(
                    fut.result())  # type: ignore
            )
        )
        await self._client.send('Tracing.end')
        self._recording = False
        return await contentPromise
项目:pyppeteer    作者:miyakogi    | 项目源码 | 文件源码
def _onExecutionContextCreated(self, context: dict) -> None:
        auxData = context.get('auxData')
        frameId = (auxData.get('frameId')
                   if auxData and auxData.get('isDefault')
                   else None)
        frame = self._frames.get(frameId)
        if not frame:
            return
        frame._defaultContextId = context.get('id', '')
        for waitTask in frame._waitTasks:
            asyncio.ensure_future(waitTask.rerun())