【问题标题】:Have two infinite task with asyncio使用 asyncio 有两个无限任务
【发布时间】:2018-09-06 08:21:21
【问题描述】:

我是 python 新手,我必须创建一个程序来保持从 web socket 和 pipe 进行 linsting,所以我需要两个异步函数。 这些函数中的每一个都在不同的线程中调用其他方法来详细说明接收到的 json 的内容。 即我在套接字线程上收到一条消息,我收到消息并抛出一个新线程来详细说明消息。
这是实际的代码:

import asyncio
import sys
import json
import websockets

# Keep listening from web socket and pipe


async def socket_receiver():
    """Listening from web socket"""
    file_socket = open(r"SocketReceived.txt", "w")
    header = {"Authorization": r"Basic XXXXXXXXXXXXXX="}
    async with websockets.connect(
            'wss://XXXXXXXXX', extra_headers=header) as web_socket:
        print("SOCKET receiving:")
        greeting = await web_socket.recv()
        json_message = json.loads(greeting)
        file_socket.write(json_message)
        print(json_message)

    file_socket.close()

async def pipe_receiver():
    """Listening from pipe"""
    file_pipe = open(r"ipeReceived.txt", "w")
    while True:
        print("PIPE receiving:")
        line = sys.stdin.readline()
        if not line:
            break

        jsonObj = json.loads(line);
        file_pipe.write(jsonObj['prova'] + '\n')
        # jsonValue = json.dump(str(line), file);
        sys.stdout.flush()

    file_pipe.close()
asyncio.get_event_loop().run_until_complete(socket_receiver())
asyncio.get_event_loop().run_until_complete(pipe_receiver())

run_until_complete 方法在我的情况下永远保留(它等待函数结束),所以只有套接字启动。 我怎样才能同时开始?谢谢

【问题讨论】:

  • Asyncio two loops for different I/O tasks? 可能重复 - 这有帮助吗?
  • 我更喜欢更清晰的解决方案,因为我有这两种监听方法,但每个收到的消息都会抛出一个新线程,我只是在看线程池

标签: python python-3.x multithreading python-asyncio


【解决方案1】:

asyncio.gather 可以解决问题,唯一的一点是两个函数应该共享同一个事件循环,并且都应该是完全异步的。

asyncio.get_event_loop().run_until_complete(
    asyncio.gather( socket_receiver(),pipe_receiver()))

从对 pipe_receiver 的快速阅读中,您将在 sys.stdin.readline 调用中挂起您的事件循环,请考虑使用 aioconsole 来异步处理输入。

【讨论】:

  • socket_receiver 不会与 websockets.connect 指令进行异步,因此即使我删除了 readline,也只有管道可以工作
  • 使用 aiohttp web socket 客户端 (aiohttp.readthedocs.io/en/v0.18.2/client_websockets.html) 而不是 websockets 数据包之一,一切都应该正常工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多