Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何同时使用Python多处理和异步IO?_Python_Python Asyncio_Python 3.7_Python Multiprocessing - Fatal编程技术网

如何同时使用Python多处理和异步IO?

如何同时使用Python多处理和异步IO?,python,python-asyncio,python-3.7,python-multiprocessing,Python,Python Asyncio,Python 3.7,Python Multiprocessing,嗨, 我有2000个api地址。 我需要在一个虚拟机中同时调用2000。 因此,我使用asyncio库修改了上述代码。 但是,这种解决办法并不令人满意。 如何提高并行处理的效果? 我想我必须同时使用多处理和异步IO。您没有具体说明“解决方案不令人满意”的含义。你有例外吗?是不是太慢了?在切换到多处理之前,您可以尝试一些事情——例如,不要为每个请求创建新的会话(客户端)。在main()中只创建一次会话,并将其传递给每个request\u test()。是的,它太慢了……而且我不明白“在main()

嗨, 我有2000个api地址。 我需要在一个虚拟机中同时调用2000。 因此,我使用asyncio库修改了上述代码。 但是,这种解决办法并不令人满意。 如何提高并行处理的效果?
我想我必须同时使用多处理和异步IO。

您没有具体说明“解决方案不令人满意”的含义。你有例外吗?是不是太慢了?在切换到多处理之前,您可以尝试一些事情——例如,不要为每个请求创建新的会话(客户端)。在
main()
中只创建一次会话,并将其传递给每个
request\u test()
。是的,它太慢了……而且我不明白“在main()和bla~中只创建一次会话”我能看到示例代码吗?将行
async with httpx.AsyncClient()作为客户端
移动到
main
函数中。将
client
作为第二个参数传递给
request\u test
,即将
request\u test(url)
替换为
request\u test(url,client)
。最后,修改
request\u test
以接受
client
作为参数。我还建议您阅读一篇关于asyncio的好的介绍,例如。这种方式需要更多的时间,可能您在服务器端受到限制,或者服务器根本无法提供您想要的吞吐量。您是否尝试过并行运行
curl
或类似程序来测量这样得到的计时?
import asyncio
import httpx
from datetime import datetime


async def request_test(url):
    async with httpx.AsyncClient() as client:
        r = await client.get(url, timeout=None, headers=None)
        return len(r.text)

async def main(rest_api_url_list ):
    futures = [asyncio.ensure_future(request_test(url)) for url in rest_api_url_list ]
    results = await asyncio.gather(*futures)
    print(results)
    print(len(results))


start = datetime.now()
rest_api_url_list = [~~~~~~~~~~~~~]    # 2000EA
loop = asyncio.get_event_loop()
loop.run_until_complete(main(rest_api_url_list ))
loop.close()
end = datetime.now()