小编Cha*_*ton的帖子

Asyncio 函数在从脚本而不是从 Flask 路由调用时起作用

我是 Python 和这些库/模块的新手。我正在编写一个简单的 ping 测试网络扫描仪作为学习项目。

我首先使用 asyncio 开发了一个脚本来 ping 网络上的地址

#ip_test.py
import asyncio
import ipaddress

async def ping(addr):
    proc = await asyncio.create_subprocess_exec(
        'ping','-W','1','-c','3',addr,
        stdout=asyncio.subprocess.PIPE
    )
    await proc.wait()
    return proc.returncode

async def pingMain(net):
    #hosts() returns list of Ipv4Address objects
    result = await asyncio.gather(*(ping(str(addr)) for addr in net.hosts()))
    return result

def getHosts(net_): #net_ is an Ipv4Network object
    return asyncio.run(pingMain(net_))
    #Returns list of response codes which I then zip with the list of searched ips
Run Code Online (Sandbox Code Playgroud)

当我打开 python 并运行以下命令时,它按预期工作:

import ip_test as iptest
import …
Run Code Online (Sandbox Code Playgroud)

python flask python-3.x python-asyncio

3
推荐指数
1
解决办法
1043
查看次数

标签 统计

flask ×1

python ×1

python-3.x ×1

python-asyncio ×1