【问题标题】:How to open 2 URLs at the same time in python如何在python中同时打开2个URL
【发布时间】:2021-05-03 15:09:24
【问题描述】:

我正在想办法同时打开两个 URL 以节省时间。 正如你在这里看到的,如果 10.10.10.2 可以访问,那么程序会关闭,如果 192.168.100.5 可以访问,那么程序会继续。 对于这个业余问题,我很抱歉,我对编程很陌生,因此对我来说很轻松。 我下面的解决方案需要很多时间,因为它一个接一个地发生。 我正在用 python 编写一个小型检查工具,以查看设备是否具有正确的 IP 地址。所以 10.10.10.2 的设备有故障,这是正确的 IP 地址 192.168.100.5。 有超过 8000 台设备需要测试,因此每台设备等待 10 秒会花费太多时间。 你们知道同时调用 2 个不同 URL 的任何其他方法吗? 我已经阅读了有关线程的信息,但是如果有人可以向我展示如何完成线程的示例,我真的不知道如何在这里应用它,我将不胜感激。 快速总结一下它应该是什么样的: 同时调用两个 URL,第一个响应的 url 决定了 python 程序是否会继续。 如果 10.10.10.2 可访问,则程序关闭,如果 192.168.100.5 可访问,则程序继续。

代码示例可能会很有帮助。

try:
    preflash = urllib.request.urlopen("http://10.10.10.2", timeout=10).getcode()
    print("Web page status code:", preflash, "FAIL")  
    sys.exit(0)
    
except urllib.error.URLError:
    correct = urllib.request.urlopen("http://192.168.100.5", timeout=10).getcode()
    print("Web page status code:", correct)
    print("IP address: 192.168.100.5 is reachable")

【问题讨论】:

  • 你尝试过创建 2 个线程吗?
  • AIOHTTP 模块可以帮助您,它允许您同时进行 aysnc 和 await 调用,因此调用 1 被放置,然后在等待响应调用 2 被放置

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


【解决方案1】:

您可以将 aiohttp 与 asyncio 一起使用。

import asyncio
import aiohttp


async def download_file(session: aiohttp.ClientSession, url: str):
    async with session.get(url) as response:
        assert response.status == 200
        # For large files use response.content.read(chunk_size) instead.
        return url, await response.read()


async def download_multiple(session: aiohttp.ClientSession):
          urls = (
              'https://stackoverflow.com/',
              'http://python.org',
          )
          download_futures = [download_file(session, url) for url in urls]
          print('Results')
          done, pending = await asyncio.wait(download_futures, return_when=asyncio.FIRST_COMPLETED)
          for task in done:
              print(task.result())
          print("unfinished:", len(pending))
          return [p.result()[0] for p in done]

async def main():
    async with aiohttp.ClientSession() as session:
      result = await download_multiple(session)
      print('finished:', result)

asyncio.run(main())

你现在可以玩 done 和 pending,done 包含第一个完成的 url,等待其他的。

main() 是一个协程,由 asyncio.run() 运行。 main() 使用 aiohttp 管理异步请求并等待 download_multiple。 download_multiple 创建一个期货(可等待对象)列表,然后使用 asyncio.wait 来“运行”它们。这里的政策是在第一个返回时返回。 asyncio.wait 返回两个任务列表,已完成(已完成)和待处理(未完成)。然后第一个已完成,其他待定。

【讨论】:

    猜你喜欢
    • 2017-08-04
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    相关资源
    最近更新 更多