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

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

项目:rci    作者:seecloud    | 项目源码 | 文件源码
def _webhook_pull_request(self, request, data):
        if data["action"] in ("opened", "reopened", "synchronize"):
            jobs_type = "cr"
        elif data["action"] == "closed":
            jobs_type = "cr-closed"
        else:
            self.root.log.debug("Skipping event %s" % data["action"])
            return
        self.root.log.info("Emiting event")
        owner = data["repository"]["owner"]
        owner_type = str(owner["type"]).encode("ascii")
        owner_id = str(owner["id"]).encode("ascii")
        if owner_type == b"Organization":
            token = self.orgs[owner_id].decode("ascii")
        else:
            token = self.users[owner_id].decode("ascii")
        client = github.Client(token)
        self.root.emit(
                Event(self.root, {}, data, client, jobs_type, data["action"]))
项目:tukio    作者:optiflows    | 项目源码 | 文件源码
def resume(self):
        """
        Resume the execution of this workflow allows new tasks to start.
        """
        if self._committed.is_set():
            log.error('Cannot resume a workflow that has not been suspended')
            return
        self._committed.set()

        # Next tasks are done waiting for '_committed' asyncio event
        # The 'suspended' ones needs to be re-executed
        for task in self._done_tasks:
            if FutureState.get(task) is not FutureState.suspended:
                continue
            event = Event(task.inputs, source=task.event_source)
            self._new_task(task.template, event)

        self._dispatch_exec_event(WorkflowExecState.RESUME)
        log.info('workflow %s has been resumed', self)
项目:tukio    作者:optiflows    | 项目源码 | 文件源码
def __init__(self, coro, *, loop=None):
        super().__init__(coro, loop=loop)
        self.holder = inspect.getcoroutinelocals(coro).get('self')
        try:
            self.uid = self.holder.uid
        except AttributeError:
            self.uid = str(uuid4())
        self._broker = get_broker(self._loop)
        self._in_progress = False
        self._template = None
        self._workflow = None
        self._source = None
        self._start = None
        self._end = None
        self._inputs = None
        self._outputs = None
        self._queue = asyncio.Queue(loop=self._loop)
        if self.holder:
            self.holder.queue = self._queue
        # A 'committed' task is a pending task not suspended
        self._committed = asyncio.Event()
        self._committed.set()
        self._timed_out = False
项目:indiechain    作者:asutoshpalai    | 项目源码 | 文件源码
def fetchBlock(self, hash):
        self.log.debug("Requesting block: " + hash)
        if hash in self._blk_wait:
            obj = self._blk_wait[hash]

            # Request is already pending
            if type(obj) is not asyncio.Event:
                return obj

            event = obj
        else:
            blk_request = block_request_packet(hash)
            self.send_data(blk_request)
            event = asyncio.Event()
            self._blk_wait[hash] = event

        yield from event.wait()

        blk = self._blk_wait[hash]
        self.log.debug("received block: " + repr(blk))
        return blk

# ex: set tabstop=4 shiftwidth=4  expandtab:
项目: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)
项目:aiomongo    作者:ZeoAlliance    | 项目源码 | 文件源码
def __init__(self, loop: asyncio.AbstractEventLoop, host: str, port: int,
                 options: ClientOptions):
        self.host = host
        self.port = port
        self.loop = loop
        self.reader = None
        self.writer = None
        self.read_loop_task = None
        self.is_mongos = False
        self.is_writable = False
        self.max_bson_size = common.MAX_BSON_SIZE
        self.max_message_size = common.MAX_MESSAGE_SIZE
        self.max_wire_version = 0
        self.max_write_batch_size = common.MAX_WRITE_BATCH_SIZE
        self.options = options
        self.slave_ok = False

        self.__connected = asyncio.Event(loop=loop)
        self.__disconnected = asyncio.Event(loop=loop)
        self.__request_id = 0
        self.__request_futures = {}
        self.__sleeper = IncrementalSleeper(loop)
项目:jd4    作者:vijos    | 项目源码 | 文件源码
def cache_open(session, domain_id, pid):
    domain_dir = path.join(_CACHE_DIR, domain_id)
    makedirs(domain_dir, exist_ok=True)
    file_path = path.join(domain_dir, pid + '.zip')
    while True:
        try:
            file = open(file_path, 'rb')
            return file
        except FileNotFoundError:
            pass
        event = _events.get((domain_id, pid))
        if not event:
            event = Event()
            _events[(domain_id, pid)] = event
            try:
                tmp_file_path = path.join(domain_dir, 'tmp_' + pid + '.zip')
                await session.problem_data(domain_id, pid, tmp_file_path)
                rename(tmp_file_path, file_path)
            finally:
                event.set()
                del _events[(domain_id, pid)]
        else:
            await event.wait()
项目:sonic-snmpagent    作者:Azure    | 项目源码 | 文件源码
def __init__(self, mib_cls, update_frequency, loop):
        if not type(mib_cls) is MIBMeta:
            raise ValueError("Expected a class with type: {}".format(MIBMeta))

        self.loop = loop

        # synchronization events
        self.run_enabled = asyncio.Event(loop=loop)
        self.oid_updaters_enabled = asyncio.Event(loop=loop)
        self.stopped = asyncio.Event(loop=loop)

        # Initialize our MIB
        self.mib_table = MIBTable(mib_cls, update_frequency)

        # containers
        self.socket_mgr = SocketManager(self.mib_table, self.run_enabled, self.loop)
项目:connectrum    作者:coinkite    | 项目源码 | 文件源码
def __init__(self, irc_nickname=None, irc_password=None, ssl=True):
        self.my_nick = irc_nickname or 'XC%d' % random.randint(1E11, 1E12)
        self.password = irc_password or None

        self.results = {}       # by hostname
        self.servers = set()
        self.all_done = asyncio.Event()

        super(IrcListener, self).__init__(host='irc.freenode.net', port=6697 if ssl else 6667, ssl=ssl)

        # setup event handling
        self.on('CLIENT_CONNECT', self.connected)
        self.on('PING', self.keepalive)
        self.on('JOIN', self.joined)
        self.on('RPL_NAMREPLY', self.got_users)
        self.on('RPL_WHOREPLY', self.got_who_reply)
        self.on("client_disconnect", self.reconnect)
        self.on('RPL_ENDOFNAMES', self.got_end_of_names)
项目:py-evm    作者:ethereum    | 项目源码 | 文件源码
def wait_ping(self, remote: Node) -> bool:
        """Wait for a ping from the given remote.

        This coroutine adds a callback to ping_callbacks and yields control until that callback is
        called or a timeout (k_request_timeout) occurs. At that point it returns whether or not
        a ping was received from the given node.
        """
        if remote in self.ping_callbacks:
            raise AlreadyWaiting(
                "There's another coroutine waiting for a ping packet from {}".format(remote))

        event = asyncio.Event()
        self.ping_callbacks[remote] = event.set
        got_ping = False
        try:
            got_ping = await asyncio.wait_for(event.wait(), k_request_timeout)
            self.logger.debug('got expected ping from {}'.format(remote))
        except asyncio.futures.TimeoutError:
            self.logger.debug('timed out waiting for ping from {}'.format(remote))
        # TODO: Use a contextmanager to ensure we always delete the callback from the list.
        del self.ping_callbacks[remote]
        return got_ping
项目:aiozk    作者:tipsi    | 项目源码 | 文件源码
def test_watch(self):
        data = []
        ready = asyncio.Event()
        test_data = b'test' * 1000

        async def data_callback(d):
            data.append(d)
            ready.set()

        watcher = self.c.recipes.DataWatcher()
        watcher.set_client(self.c)
        watcher.add_callback(self.path, data_callback)
        assert data == []
        await self.c.set_data(self.path, test_data)
        await asyncio.wait([ready.wait()], timeout=0.1)
        assert ready.is_set()
        assert data == [test_data]
项目:aiozk    作者:tipsi    | 项目源码 | 文件源码
def test_watch(self):
        children = set()
        ready = asyncio.Event()

        async def children_callback(c):
            for child in c:
                children.add(child)
                ready.set()

        watcher = self.c.recipes.ChildrenWatcher()
        watcher.set_client(self.c)
        watcher.add_callback(self.path, children_callback)
        assert children == set()
        await self.c.create(self.child_1)
        await asyncio.wait([ready.wait()], timeout=0.1)
        assert children == {self.child_1.split('/')[-1]}
        ready.clear()
        await self.c.create(self.child_2)
        await asyncio.wait([ready.wait()], timeout=0.1)
        assert ready.is_set()
        assert children == {child.split('/')[-1] for child in (self.child_1, self.child_2)}
项目:azmq    作者:ereOn    | 项目源码 | 文件源码
def connection(event_loop):
    class MyConnection(BaseConnection):
        def __init__(self, **kwargs):
            super().__init__(**kwargs)
            self.done = asyncio.Event(loop=event_loop)

        async def on_run(self):
            await self.done.wait()

    connection = MyConnection(
        socket_type=b'REQ',
        identity=b'myconnection',
        mechanism=MagicMock(),
        on_ready=MagicMock(),
        on_lost=MagicMock(),
        on_failure=MagicMock(),
        loop=event_loop,
    )
    yield connection
    connection.done.set()
项目:dogbot    作者:slice    | 项目源码 | 文件源码
def __init__(self, bot, name: str):
        #: The name of this :class:`AsyncQueue`.
        self.name = name

        #: The bot instance to use.
        self.bot = bot

        #: The current item being processed, if any.
        self.current_item = None

        #: The :class:`asyncio.Task` that handles items.
        self.handler = bot.loop.create_task(self.handle())

        #: A :class:`asyncio.Event` that is set as long as we have an item.
        self.has_item = asyncio.Event()

        self._log('debug', 'Created!')
项目:metapensiero.reactive    作者:azazel75    | 项目源码 | 文件源码
def __init__(self, source=None, *, push_mode=False, loop=None,
                 remove_none=False, await_send=False):
        self.loop = loop or asyncio.get_event_loop()
        self._mode = TEE_MODE.PUSH if push_mode else TEE_MODE.PULL
        if self._mode == TEE_MODE.PULL:
            self._status = TEE_STATUS.INITIAL
        else:
            self._status = TEE_STATUS.STARTED
        super().__init__(source)
        self._queues = {}
        self._run_fut = None
        self._send_queue = collections.deque()
        self._send_cback = push_mode
        self._send_avail = asyncio.Event(loop=self.loop)
        self._remove_none = remove_none
        self._await_send = await_send
项目:aiotk    作者:AndreLouisCaron    | 项目源码 | 文件源码
def test_pool_auto_cancel(event_loop):
    """Lingering tasks are automatically cancelled."""

    ready = asyncio.Event(loop=event_loop)

    async def child_task():
        ready.set()
        await wait_until_cancelled(loop=event_loop)

    async with TaskPool(loop=event_loop) as pool:
        task = await pool.spawn(child_task)
        await ready.wait()
        assert not task.done()

    # The task should have been cancelled.
    assert task.done()
    assert task.cancelled()
    with pytest.raises(asyncio.CancelledError):
        print(task.result())
项目:aiotk    作者:AndreLouisCaron    | 项目源码 | 文件源码
def test_pool_collect(event_loop):
    """Cancelled tasks are collected by the pool."""

    ready = asyncio.Event(loop=event_loop)

    async def child_task():
        ready.set()

    async with TaskPool(loop=event_loop) as pool:
        task = await pool.spawn(child_task)
        await ready.wait()

        # Let the loop complete before we cancel it.
        await pool.wait_idle()

    assert task.done()
    assert not task.cancelled()
    assert task.result() is None
项目:aiotk    作者:AndreLouisCaron    | 项目源码 | 文件源码
def test_pool_collect_cancelled(event_loop):
    """Cancelled tasks are collected by the pool."""

    ready = asyncio.Event(loop=event_loop)

    async def child_task():
        ready.set()
        await wait_until_cancelled(loop=event_loop)

    async with TaskPool(loop=event_loop) as pool:
        task = await pool.spawn(child_task)
        await ready.wait()
        assert not task.done()
        await cancel(task)

        # The task should have been cancelled.
        assert task.done()
        assert task.cancelled()

        # Let the loop complete before we cancel it.
        await pool.wait_idle()
项目:aiotk    作者:AndreLouisCaron    | 项目源码 | 文件源码
def test_pool_spawn_while_waiting(event_loop):
    """Spawning tasks unblocks to update the watch set."""

    done = asyncio.Event(loop=event_loop)

    async def child_task():
        await done.wait()

    async with TaskPool(loop=event_loop) as pool:

        # Spawn a first task.
        await pool.spawn(child_task)

        # Wait until the pool is blocked.
        await pool.wait_busy()

        # Spawn a second task.
        await pool.spawn(child_task)

        # Unblock both tasks and let them finish.
        done.set()
        await pool.wait_idle()
项目:aiotk    作者:AndreLouisCaron    | 项目源码 | 文件源码
def test_wait_until_cancelled_propagate(event_loop):
    """CancelledError exception is propagated by default."""

    child_ready = asyncio.Event(loop=event_loop)

    async def child_task():
        child_ready.set()
        await wait_until_cancelled(loop=event_loop)

    task = event_loop.create_task(child_task())
    await child_ready.wait()

    assert not task.done()
    await cancel(task)
    assert task.done()
    assert task.cancelled()
    with pytest.raises(asyncio.CancelledError):
        print(task.result())
项目:aiotk    作者:AndreLouisCaron    | 项目源码 | 文件源码
def test_wait_until_cancelled_silence(event_loop):
    """CancelledError exception can be silenced."""

    child_ready = asyncio.Event(loop=event_loop)

    async def child_task():
        child_ready.set()
        await wait_until_cancelled(propagate=False, loop=event_loop)

    task = event_loop.create_task(child_task())
    await child_ready.wait()

    assert not task.done()
    await cancel(task)
    assert task.done()
    assert not task.cancelled()
    assert task.result() is None
项目:aiotk    作者:AndreLouisCaron    | 项目源码 | 文件源码
def test_periodic_task_cancelled_while_task_is_running(event_loop):
    """The background task is cancelled."""

    ready = asyncio.Event(loop=event_loop)
    close = asyncio.Event(loop=event_loop)

    async def task():
        ready.set()
        await close.wait()

    with mock.patch('asyncio.sleep') as sleep:
        sleep.return_value = None
        async with PeriodicTask(task, 0.01, loop=event_loop):
            await ready.wait()

    assert sleep.call_args_list == []
项目:sanic    作者:channelcat    | 项目源码 | 文件源码
def test_websocket_route():
    app = Sanic('test_websocket_route')
    ev = asyncio.Event()

    @app.websocket('/ws')
    async def handler(request, ws):
        assert ws.subprotocol is None
        ev.set()

    request, response = app.test_client.get('/ws', headers={
        'Upgrade': 'websocket',
        'Connection': 'upgrade',
        'Sec-WebSocket-Key': 'dGhlIHNhbXBsZSBub25jZQ==',
        'Sec-WebSocket-Version': '13'})
    assert response.status == 101
    assert ev.is_set()
项目:aioetcd3    作者:gaopeiliang    | 项目源码 | 文件源码
def __init__(self, event, revision):
        if event.type == kv.Event.PUT:
            if event.kv.version == 1:
                self.type = EVENT_TYPE_CREATE
            else:
                self.type = EVENT_TYPE_MODIFY
        else:
            self.type = EVENT_TYPE_DELETE

        self.key = event.kv.key
        self.value = event.kv.value
        self.meta = KVMetadata(event.kv)

        self.pre_value = event.prev_kv.value
        self.pre_meta = KVMetadata(event.prev_kv)

        self.revision = revision
项目:amqproto    作者:malinoff    | 项目源码 | 文件源码
def __init__(self, host='localhost', port=5672, *,
                 ssl=None, flags=0, sock=None, local_addr=None,
                 server_hostname=None, **kwargs):
        super().__init__(writer=None, **kwargs)
        self._reader = None
        self._connect_args = {
            'host': host,
            'port': port,
            'ssl': ssl,
            'flags': flags,
            'sock': sock,
            'local_addr': local_addr,
            'server_hostname': server_hostname,
        }
        self._negotiation = asyncio.Event()
        self._heartbeat_task = None
        self._communicate_task = None
项目:morphis    作者:bitcoinembassy    | 项目源码 | 文件源码
def __init__(self, engine, data_callback, ordered=False, positions=None,\
            retry_seconds=30, concurrency=64):
        self.engine = engine
        self.data_callback = data_callback
        self.ordered = ordered
        self.positions = positions
        self.retry_seconds = retry_seconds
        self.concurrency = concurrency

        self._task_semaphore = asyncio.Semaphore(concurrency)
        self._next_position = 0
        self._failed = deque()
        self._ordered_waiters = []
        self._ordered_waiters_dc = {} #FIXME: WTF is this?

        self._task_cnt = 0
        self._tasks_done = asyncio.Event()

        self._abort = False
项目:Bonfire    作者:Phxntxm    | 项目源码 | 文件源码
def __init__(self, bot, download):
        self.current = None
        self.voice = None
        self.bot = bot
        self.play_next_song = asyncio.Event()
        # This is the queue that holds all VoiceEntry's
        self.songs = Playlist(bot)
        self.required_skips = 0
        # a set of user_ids that voted
        self.skip_votes = set()
        # Our actual task that handles the queue system
        self.audio_player = self.bot.loop.create_task(self.audio_player_task())
        self.opts = {
            'default_search': 'auto',
            'quiet': True
        }
        self.volume = 50
        self.downloader = download
        self.file_names = []
项目:electrumx    作者:kyuupichan    | 项目源码 | 文件源码
def __init__(self, env):
        super().__init__()
        self.coin = env.coin
        self.set_urls(env.coin.daemon_urls(env.daemon_url))
        self._height = None
        self._mempool_hashes = set()
        self.mempool_refresh_event = asyncio.Event()
        # Limit concurrent RPC calls to this number.
        # See DEFAULT_HTTP_WORKQUEUE in bitcoind, which is typically 16
        self.workqueue_semaphore = asyncio.Semaphore(value=10)
        self.down = False
        self.last_error_time = 0
        self.req_id = 0
        # assignment of asyncio.TimeoutError are essentially ignored
        if aiohttp.__version__.startswith('1.'):
            self.ClientHttpProcessingError = aiohttp.ClientHttpProcessingError
            self.ClientPayloadError = asyncio.TimeoutError
        else:
            self.ClientHttpProcessingError = asyncio.TimeoutError
            self.ClientPayloadError = aiohttp.ClientPayloadError
        self._available_rpcs = {}  # caches results for _is_rpc_available()
项目:jose    作者:lnmds    | 项目源码 | 文件源码
def __init__(self, webhook, *, level=None, loop=None):
        if level is not None:
            super().__init__(level)
        else:
            super().__init__()

        self.webhook = webhook
        self.loop = loop = loop or asyncio.get_event_loop()

        self.closed = False

        self._buffer = []

        self._last_emit = 0
        self._can_emit = asyncio.Event()

        self._emit_task = loop.create_task(self.emitter())
项目:jose    作者:lnmds    | 项目源码 | 文件源码
def __init__(self, ctx, target):
        self.ctx = ctx
        self.bot = ctx.bot
        self.heist = ctx.cog
        self.id = ctx.guild.id

        self.cext = ctx.bot.get_cog('CoinsExt')
        self.coins = ctx.bot.get_cog('Coins')
        # self.SayException = SayException

        self.target = target
        self.amount = 0

        self.users = []
        self.started = False
        self.finish = asyncio.Event()
        self.task = None
项目:asyncpg    作者:MagicStack    | 项目源码 | 文件源码
def _start(self, started_event):
        self.loop = asyncio.new_event_loop()

        self.connectivity = asyncio.Event(loop=self.loop)
        self.connectivity.set()
        self.connectivity_loss = asyncio.Event(loop=self.loop)
        self.stop_event = asyncio.Event(loop=self.loop)

        if self.listening_port is None:
            self.listening_port = cluster.find_available_port()

        self.sock = socket.socket()
        self.sock.bind((self.listening_addr, self.listening_port))
        self.sock.listen(50)
        self.sock.setblocking(False)

        try:
            self.loop.run_until_complete(self._main(started_event))
        finally:
            self.loop.close()
项目:cappy    作者:DanielSank    | 项目源码 | 文件源码
def main(host, port, as_server):
    if as_server:
        main = main_server
    else:
        main = main_client

    loop = asyncio.get_event_loop()
    done = asyncio.Event()

    future = loop.create_task(main(
        loop,
        default_connection_factory,
        done,
        host,
        port))
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    done.set()
    loop.run_until_complete(future)
    loop.close()
项目:necrobot    作者:incnone    | 项目源码 | 文件源码
def send_and_get_rate_limit(
        client: discord.Client,
        channel: discord.Channel,
        content: str
):
    global global_over
    global_over = asyncio.Event(loop=asyncio.get_event_loop())
    global_over.set()

    channel_id, guild_id = yield from client._resolve_destination(channel)

    rate_limit_info = RateLimitInfo()
    data = yield from send_message(client.http, channel_id, content, rate_limit_info)
    channel = client.get_channel(data.get('channel_id'))
    # noinspection PyArgumentList
    message = client.connection._create_message(channel=channel, **data)
    return message, rate_limit_info
项目:aioh2    作者:decentfox    | 项目源码 | 文件源码
def __init__(self, stream_id, window_getter, loop=None):
        if loop is None:
            loop = asyncio.get_event_loop()
        self._stream_id = stream_id
        self._window_getter = window_getter

        self._wlock = asyncio.Lock(loop=loop)
        self._window_open = CallableEvent(self._is_window_open, loop=loop)

        self._rlock = asyncio.Lock(loop=loop)
        self._buffers = deque()
        self._buffer_size = 0
        self._buffer_ready = asyncio.Event(loop=loop)
        self._response = asyncio.Future(loop=loop)
        self._trailers = asyncio.Future(loop=loop)
        self._eof_received = False
        self._closed = False
项目:yacron    作者:gjcarneiro    | 项目源码 | 文件源码
def __init__(self, config_arg: Optional[str], *,
                 config_yaml: Optional[str]=None
                 ) -> None:
        # list of cron jobs we /want/ to run
        self.cron_jobs = OrderedDict()  # type: Dict[str, JobConfig]
        # list of cron jobs already running
        # name -> list of RunningJob
        self.running_jobs = \
            defaultdict(list)  # type: Dict[str, List[RunningJob]]
        self.config_arg = config_arg
        if config_arg is not None:
            self.update_config()
        if config_yaml is not None:
            # config_yaml is for unit testing
            config = parse_config_string(config_yaml)
            self.cron_jobs = OrderedDict((job.name, job) for job in config)

        self._wait_for_running_jobs_task = None  # type: Optional[asyncio.Task]
        self._stop_event = asyncio.Event()
        self._jobs_running = asyncio.Event()
        self.retry_state = {}  # type: Dict[str, JobRetryState]
项目:aioimaplib    作者:bamthomas    | 项目源码 | 文件源码
def __init__(self, name, tag, *args, prefix=None, untagged_resp_name=None, loop=asyncio.get_event_loop(), timeout=None):
        self.name = name
        self.tag = tag
        self.args = args
        self.prefix = prefix + ' ' if prefix else None
        self.untagged_resp_name = untagged_resp_name or name

        self.response = None
        self._exception = None
        self._event = asyncio.Event(loop=loop)
        self._loop = loop
        self._timeout = timeout
        self._timer = asyncio.Handle(lambda: None, None, loop)  # fake timer
        self._set_timer()
        self._literal_data = None
        self._expected_size = 0
项目:python-libjuju    作者:juju    | 项目源码 | 文件源码
def __init__(self, connection):
        self.connection = weakref.ref(connection)
        self.reconnecting = asyncio.Lock(loop=connection.loop)
        self.close_called = asyncio.Event(loop=connection.loop)
项目:python-libjuju    作者:juju    | 项目源码 | 文件源码
def __init__(self, task, loop):
        self.stopped = asyncio.Event(loop=loop)
        self.stopped.set()
        self.task = task
        self.loop = loop
项目:python-libjuju    作者:juju    | 项目源码 | 文件源码
def __init__(
        self,
        loop=None,
        max_frame_size=None,
        bakery_client=None,
        jujudata=None,
    ):
        """Instantiate a new Model.

        The connect method will need to be called before this
        object can be used for anything interesting.

        If jujudata is None, jujudata.FileJujuData will be used.

        :param loop: an asyncio event loop
        :param max_frame_size: See
            `juju.client.connection.Connection.MAX_FRAME_SIZE`
        :param bakery_client httpbakery.Client: The bakery client to use
            for macaroon authorization.
        :param jujudata JujuData: The source for current controller information.
        """
        self._connector = connector.Connector(
            loop=loop,
            max_frame_size=max_frame_size,
            bakery_client=bakery_client,
            jujudata=jujudata,
        )
        self._observers = weakref.WeakValueDictionary()
        self.state = ModelState(self)
        self._info = None
        self._watch_stopping = asyncio.Event(loop=self._connector.loop)
        self._watch_stopped = asyncio.Event(loop=self._connector.loop)
        self._watch_received = asyncio.Event(loop=self._connector.loop)
        self._watch_stopped.set()
        self._charmstore = CharmStore(self._connector.loop)
项目:python-libjuju    作者:juju    | 项目源码 | 文件源码
def run_with_interrupt(task, event, loop=None):
    """
    Awaits a task while allowing it to be interrupted by an `asyncio.Event`.

    If the task finishes without the event becoming set, the results of the
    task will be returned.  If the event becomes set, the task will be
    cancelled ``None`` will be returned.

    :param task: Task to run
    :param event: An `asyncio.Event` which, if set, will interrupt `task`
        and cause it to be cancelled.
    :param loop: Optional event loop to use other than the default.
    """
    loop = loop or asyncio.get_event_loop()
    event_task = loop.create_task(event.wait())
    done, pending = await asyncio.wait([task, event_task],
                                       loop=loop,
                                       return_when=asyncio.FIRST_COMPLETED)
    for f in pending:
        f.cancel()
    exception = [f.exception() for f in done
                 if f is not event_task and f.exception()]
    if exception:
        raise exception[0]
    result = [f.result() for f in done if f is not event_task]
    if result:
        return result[0]
    else:
        return None
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def __init__(self, bot):
        super().__init__()
        self.bot = bot
        self.stream = None
        self.feeds = {}
        self.reconnect_ready = asyncio.Event()
        self.reconnect_ready.set()
        self.reconnecting = False
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def initialize(self, client, text_channel, white_player, black_player):
        self.bot = client
        self.text_channel = text_channel
        self.white_player = white_player
        self.black_player = black_player
        self.chess_engine = chess.uci.popen_engine("bin/stockfish_8_x64.exe")
        #self.chess_engine = chess.uci.popen_engine("bin/stockfish_8_x64_popcnt.exe")
        self.chess_engine.uci()
        self.match_message = None
        self.match_embed = None
        self.generated_move = asyncio.Event()
        self.best_move = None
        self.ponder = None
        self.task = self.bot.loop.create_task(self.match_task())
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def __init__(self, client, text_channel):
        self.bot = client
        self.text_channel = text_channel
        self.server = text_channel.server
        self.queue = asyncio.Queue()
        self.current = None
        self.play_next_song = asyncio.Event()
        self.ytdl_options = {"default_search": "auto", "noplaylist": True, "quiet": True, 
            "format": "webm[abr>0]/bestaudio/best", "prefer_ffmpeg": True}
        self.ytdl_download_options = {"default_search": "auto", "noplaylist": True, "quiet": True, 
            "format": "bestaudio/best", "extractaudio": True, "outtmpl": "data/audio_cache/%(id)s-%(title)s.%(ext)s", "restrictfilenames": True} # "audioformat": "mp3" ?
        self.ytdl_playlist_options = {"default_search": "auto", "extract_flat": True, "forcejson": True, "quiet": True, 
            "logger": playlist_logger}
        self.default_volume = 100.0
        self.skip_votes_required = 0
        self.skip_votes = set()
        self.player = self.bot.loop.create_task(self.player_task())
        self.resume_flag = asyncio.Event()
        self.not_interrupted = asyncio.Event()
        self.not_interrupted.set()
        self.audio_files = os.listdir("data/audio_files/")
        self.library_files = [f for f in os.listdir(clients.library_files) if f.endswith((".mp3", ".m4a"))]
        self.library_flag = False
        self.radio_flag = False
        self.recognizer = speech_recognition.Recognizer()
        self.listener = None
        self.listen_paused = False
        self.previous_played_time = 0
项目:CorpBot.py    作者:corpnewt    | 项目源码 | 文件源码
def __init__(self, bot, settings):
        self.current = None
        self.voice = None
        self.bot = bot
        self.play_next_song = asyncio.Event()
        self.playlist = []
        self.repeat = False
        self.votes = []
        self.audio_player = self.bot.loop.create_task(self.audio_player_task())
        self.start_time = datetime.datetime.now()
        self.total_playing_time = datetime.datetime.now() - datetime.datetime.now()
        self.is_paused = False
        self.settings = settings
项目:CorpBot.py    作者:corpnewt    | 项目源码 | 文件源码
def newcah(self, ctx):
        """Starts a new Cards Against Humanity game."""
        #if not await self.checkPM(ctx.message):
            #return
        # Check if the user is already in game
        userGame = self.userGame(ctx.message.author)
        if userGame:
            # Already in a game
            msg = "You're already in a game (id: *{}*)\nType `{}leavecah` to leave that game.".format(userGame['ID'], ctx.prefix)
            await self.bot.send_message(ctx.message.channel, msg)
            return

        # Not in a game - create a new one
        gameID = self.randomID()
        currentTime = int(time.time())
        newGame = { 'ID': gameID, 'Members': [], 'Discard': [], 'BDiscard': [], 'Judge': -1, 'Time': currentTime, 'BlackCard': None, 'Submitted': [], 'NextHand': asyncio.Event(), 'Judging': False, 'Timeout': True }
        member = { 'ID': ctx.message.author.id, 'User': ctx.message.author, 'Points': 0, 'Won': [], 'Hand': [], 'Laid': False, 'Refreshed': False, 'IsBot': False, 'Creator': True, 'Task': None, 'Time': currentTime }
        newGame['Members'].append(member)
        newGame['Running'] = True
        task = self.bot.loop.create_task(self.gameCheckLoop(ctx, newGame))
        task = self.bot.loop.create_task(self.checkCards(ctx, newGame))
        self.games.append(newGame)
        # Tell the user they created a new game and list its ID
        await self.bot.send_message(ctx.message.channel, 'You created game id: *{}*'.format(gameID))
        await self.drawCards(ctx.message.author)
        # await self.showHand(ctx, ctx.message.author)
        # await self.nextPlay(ctx, newGame)
项目:win32wifi    作者:kedos    | 项目源码 | 文件源码
def main():
    ifaces = getWirelessInterfaces()
    for iface in ifaces:
        print(iface.guid)

    print("Registering...")
    registerNotification(demo)
    print("Done.")

    yield from asyncio.Event().wait()
项目:jenkins-epo    作者:peopledoc    | 项目源码 | 文件源码
def __init__(self, *a, **kw):
        super(JoinableQueueMixin, self).__init__(*a, **kw)
        self._pending_tasks = 0
        self._finished = asyncio.Event()
项目:Ruby-Bot    作者:ahuei123456    | 项目源码 | 文件源码
def __init__(self, bot):
        self.current = None
        self.voice = None
        self.bot = bot
        self.play_next_song = asyncio.Event()
        self.songs = asyncio.Queue()
        self.skip_votes = set() # a set of user_ids that voted
        self.audio_player = self.bot.loop.create_task(self.audio_player_task())
项目:uchroma    作者:cyanogen    | 项目源码 | 文件源码
def __init__(self, frame: Frame, default_blend_mode: str=None,
                 *args, **kwargs):
        super(AnimationLoop, self).__init__(*args, **kwargs)

        self._frame = frame
        self._default_blend_mode = default_blend_mode

        self._anim_task = None

        self._pause_event = asyncio.Event()
        self._pause_event.set()

        self._logger = frame._driver.logger
        self._error = False
        self.layers_changed = Signal()
项目:aiotasks    作者:cr0hn    | 项目源码 | 文件源码
def __init__(self,
                 loop,
                 prefix: str = "aiotasks"):
        self._loop_subscribers = loop
        self.prefix = prefix

        self.running_tasks = dict()
        self.topics_subscribers = defaultdict(set)
        self.subscriber_ready = asyncio.Event(loop=self._loop_subscribers)