當前位置: 首頁>>代碼示例>>Python>>正文


Python asyncio.sleep方法代碼示例

本文整理匯總了Python中asyncio.sleep方法的典型用法代碼示例。如果您正苦於以下問題:Python asyncio.sleep方法的具體用法?Python asyncio.sleep怎麽用?Python asyncio.sleep使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在asyncio的用法示例。


在下文中一共展示了asyncio.sleep方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_websocket_non_regression_bug_105

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import sleep [as 別名]
def test_websocket_non_regression_bug_105(event_loop, server):

    # This test will check a fix to a race condition which happens if the user is trying
    # to connect using the same client twice at the same time
    # See bug #105

    url = f"ws://{server.hostname}:{server.port}/graphql"
    print(f"url = {url}")

    sample_transport = WebsocketsTransport(url=url)

    client = Client(transport=sample_transport)

    # Create a coroutine which start the connection with the transport but does nothing
    async def client_connect(client):
        async with client:
            await asyncio.sleep(2 * MS)

    # Create two tasks which will try to connect using the same client (not allowed)
    connect_task1 = asyncio.ensure_future(client_connect(client))
    connect_task2 = asyncio.ensure_future(client_connect(client))

    with pytest.raises(TransportAlreadyConnected):
        await asyncio.gather(connect_task1, connect_task2) 
開發者ID:graphql-python,項目名稱:gql,代碼行數:26,代碼來源:test_websocket_exceptions.py

示例2: test_websocket_sending_invalid_payload

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import sleep [as 別名]
def test_websocket_sending_invalid_payload():

    # Get Websockets transport
    sample_transport = WebsocketsTransport(
        url="wss://countries.trevorblades.com/graphql", ssl=True
    )

    # Instanciate client
    async with Client(transport=sample_transport):

        invalid_payload = '{"id": "1", "type": "start", "payload": "BLAHBLAH"}'

        print(f">>> {invalid_payload}")
        await sample_transport.websocket.send(invalid_payload)

        await asyncio.sleep(2) 
開發者ID:graphql-python,項目名稱:gql,代碼行數:18,代碼來源:test_websocket_online.py

示例3: server_countdown_close_connection_in_middle

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import sleep [as 別名]
def server_countdown_close_connection_in_middle(ws, path):
    await WebSocketServer.send_connection_ack(ws)

    result = await ws.recv()
    json_result = json.loads(result)
    assert json_result["type"] == "start"
    payload = json_result["payload"]
    query = payload["query"]
    query_id = json_result["id"]

    count_found = search("count: {:d}", query)
    count = count_found[0]
    stopping_before = count // 2
    print(f"Countdown started from: {count}, stopping server before {stopping_before}")
    for number in range(count, stopping_before, -1):
        await ws.send(countdown_server_answer.format(query_id=query_id, number=number))
        await asyncio.sleep(2 * MS)

    print("Closing server while subscription is still running now")
    await ws.close()
    await ws.wait_closed()
    print("Server is now closed") 
開發者ID:graphql-python,項目名稱:gql,代碼行數:24,代碼來源:test_websocket_subscription.py

示例4: test_websocket_subscription_slow_consumer

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import sleep [as 別名]
def test_websocket_subscription_slow_consumer(
    event_loop, client_and_server, subscription_str
):

    session, server = client_and_server

    count = 10
    subscription = gql(subscription_str.format(count=count))

    async for result in session.subscribe(subscription):
        await asyncio.sleep(10 * MS)

        number = result["number"]
        print(f"Number received: {number}")

        assert number == count

        count -= 1

    assert count == -1 
開發者ID:graphql-python,項目名稱:gql,代碼行數:22,代碼來源:test_websocket_subscription.py

示例5: server_starwars

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import sleep [as 別名]
def server_starwars(ws, path):
    await WebSocketServer.send_connection_ack(ws)

    try:
        await ws.recv()

        reviews = [starwars_expected_one, starwars_expected_two]

        for review in reviews:

            data = (
                '{"type":"data","id":"1","payload":{"data":{"reviewAdded": '
                + json.dumps(review)
                + "}}}"
            )
            await ws.send(data)
            await asyncio.sleep(2 * MS)

        await WebSocketServer.send_complete(ws, 1)
        await WebSocketServer.wait_connection_terminate(ws)

    except websockets.exceptions.ConnectionClosedOK:
        pass

    print("Server is now closed") 
開發者ID:graphql-python,項目名稱:gql,代碼行數:27,代碼來源:test_async_client_validation.py

示例6: manipulate_condition

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import sleep [as 別名]
def manipulate_condition(condition):
    print('starting manipulate_condition')

    # pause to let consumers start
    await asyncio.sleep(0.1)

    for i in range(1, 3):
        with await condition:
            print('notifying {} consumers'.format(i))
            condition.notify(n=i)
        await asyncio.sleep(0.1)

    with await condition:
        print('notifying remaining consumers')
        condition.notify_all()

    print('ending manipulate_condition') 
開發者ID:PacktPublishing,項目名稱:Learning-Concurrency-in-Python,代碼行數:19,代碼來源:asyncioCondition.py

示例7: patcher

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import sleep [as 別名]
def patcher(self):
        await self.bot.wait_until_ready()
        try:
            await asyncio.sleep(6)  # be safe lolz
            while True:
                if not hasattr(self.bot.send_message, 'old'):
                    print(
                        '[WARNING:] -- Overwriting bot.send_message with '
                        'send_lolz. If bot.send_message is not reloaded,')
                    print(
                        '[WARNING:] -- in the event of a crash of the lolz '
                        'cog, you may not be able revert to bot.send_message '
                        'without a restart/reloading lolz')
                    self.bot.send_message = self.send_lolz(self.bot.send_message)
                await asyncio.sleep(1)
        except asyncio.CancelledError:
            pass 
開發者ID:irdumbs,項目名稱:Dumb-Cogs,代碼行數:19,代碼來源:lolz.py

示例8: hal

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import sleep [as 別名]
def hal(self, ctx, *, question="none"):
        """Speak with HAL"""
        author = ctx.message.author
        msg = ""
        found = []
        for k,v in self.responses.items():
            if k in question.lower():
                found.append(v)
        if found:
            msg = randchoice(randchoice(found))
        if not msg:
            msg = randchoice(self.responses["none"])
        await asyncio.sleep(1)
        await self.bot.say(msg.format(author=author))
        if "sing it for me" in question.lower() and "Audio" in self.bot.cogs and author.voice_channel:
            audio = self.bot.get_cog("Audio")
            if audio.music_player.is_done():
                link = "https://www.youtube.com/watch?v=hchUl3QlJZE"
                # probably dont need. just too lazy to check.
                ctx.message.content = "{}play {}".format(ctx.prefix, link)
                if await audio.check_voice(ctx.message.author, ctx.message):
                    audio.queue.append(link) 
開發者ID:irdumbs,項目名稱:Dumb-Cogs,代碼行數:24,代碼來源:hal.py

示例9: check_output_is_expected

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import sleep [as 別名]
def check_output_is_expected(directory, capsys):
    """Create, move, and delete a file."""
    # Create file
    original_filename = os.path.join(directory, 'file.txt')
    pathlib.Path(original_filename).touch()
    await asyncio.sleep(0.1)  # force release to stdout
    captured = capsys.readouterr()
    assert captured.out == 'File created!\n'
    # Move file
    new_filename = os.path.join(directory, 'new_filename.txt')
    os.rename(original_filename, new_filename)
    await asyncio.sleep(0.1)  # force release to stdout
    captured = capsys.readouterr()
    assert captured.out == 'File moved!\n'
    # Delete file
    os.remove(new_filename)
    await asyncio.sleep(0.1)  # force release to stdout
    captured = capsys.readouterr()
    assert captured.out == 'File deleted!\n' 
開發者ID:biesnecker,項目名稱:hachiko,代碼行數:21,代碼來源:test_hachiko.py

示例10: test_should_automatically_send_a_typing_indicator

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import sleep [as 別名]
def test_should_automatically_send_a_typing_indicator(self):
        async def aux(context):
            await asyncio.sleep(0.600)
            await context.send_activity(f"echo:{context.activity.text}")

        def assert_is_typing(activity, description):  # pylint: disable=unused-argument
            assert activity.type == ActivityTypes.typing

        adapter = TestAdapter(aux)
        adapter.use(ShowTypingMiddleware())

        step1 = await adapter.send("foo")
        step2 = await step1.assert_reply(assert_is_typing)
        step3 = await step2.assert_reply("echo:foo")
        step4 = await step3.send("bar")
        step5 = await step4.assert_reply(assert_is_typing)
        await step5.assert_reply("echo:bar") 
開發者ID:microsoft,項目名稱:botbuilder-python,代碼行數:19,代碼來源:test_show_typing_middleware.py

示例11: test_get_clan_battles

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import sleep [as 別名]
def test_get_clan_battles(self):
        """This test will test out:
        - Normal clan battles fetching
        - All battles fetching
        - Clan war battles only fetching
        """

        tag = '29UQQ282'
        battles = await self.cr.get_clan_battles(tag)
        self.assertTrue(isinstance(battles, list))
        await asyncio.sleep(2)
        battles = await self.cr.get_clan_battles(tag, type='all')
        self.assertTrue(isinstance(battles, list))
        await asyncio.sleep(2)
        battles = await self.cr.get_clan_battles(tag, type='war')
        self.assertTrue(isinstance(battles, list)) 
開發者ID:cgrok,項目名稱:clashroyale,代碼行數:18,代碼來源:test_async.py

示例12: test_websocket_sending_invalid_data

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import sleep [as 別名]
def test_websocket_sending_invalid_data(event_loop, client_and_server, query_str):

    session, server = client_and_server

    invalid_data = "QSDF"
    print(f">>> {invalid_data}")
    await session.transport.websocket.send(invalid_data)

    await asyncio.sleep(2 * MS) 
開發者ID:graphql-python,項目名稱:gql,代碼行數:11,代碼來源:test_websocket_exceptions.py

示例13: test_websocket_server_sending_invalid_query_errors

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import sleep [as 別名]
def test_websocket_server_sending_invalid_query_errors(event_loop, server):
    url = f"ws://{server.hostname}:{server.port}/graphql"
    print(f"url = {url}")

    sample_transport = WebsocketsTransport(url=url)

    # Invalid server message is ignored
    async with Client(transport=sample_transport):
        await asyncio.sleep(2 * MS) 
開發者ID:graphql-python,項目名稱:gql,代碼行數:11,代碼來源:test_websocket_exceptions.py

示例14: test_websocket_sending_invalid_data

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import sleep [as 別名]
def test_websocket_sending_invalid_data():

    # Get Websockets transport
    sample_transport = WebsocketsTransport(
        url="wss://countries.trevorblades.com/graphql", ssl=True
    )

    # Instanciate client
    async with Client(transport=sample_transport) as session:

        query = gql(
            """
            query getContinents {
              continents {
                code
              }
            }
        """
        )

        # Execute query
        result = await session.execute(query)

        print(f"result = {result!r}")

        invalid_data = "QSDF"
        print(f">>> {invalid_data}")
        await sample_transport.websocket.send(invalid_data)

        await asyncio.sleep(2) 
開發者ID:graphql-python,項目名稱:gql,代碼行數:32,代碼來源:test_websocket_online.py

示例15: test_websocket_subscription_task_cancel

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import sleep [as 別名]
def test_websocket_subscription_task_cancel(
    event_loop, client_and_server, subscription_str
):

    session, server = client_and_server

    count = 10
    subscription = gql(subscription_str.format(count=count))

    async def task_coro():
        nonlocal count
        async for result in session.subscribe(subscription):

            number = result["number"]
            print(f"Number received: {number}")

            assert number == count

            count -= 1

    task = asyncio.ensure_future(task_coro())

    async def cancel_task_coro():
        nonlocal task

        await asyncio.sleep(11 * MS)

        task.cancel()

    cancel_task = asyncio.ensure_future(cancel_task_coro())

    await asyncio.gather(task, cancel_task)

    assert count > 0 
開發者ID:graphql-python,項目名稱:gql,代碼行數:36,代碼來源:test_websocket_subscription.py


注:本文中的asyncio.sleep方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。