相关疑难解决方法(0)

Python asyncio:在工作线程上运行subprocess_exec

所以我使用Python asyncio模块(在Linux上)启动子进程,然后异步监视它.我的代码工作正常...在主线程上运行时.但是当我在工作线程上运行它时,它会挂起,并且process_exited永远不会调用回调.

我怀疑这可能实际上是某种未记录的缺陷或subprocess_exec在工作线程上运行的问题,可能与实现如何处理后台线程中的信号有关.但它也可能只是让我搞砸了.

一个简单,可重复的例子如下:

class MyProtocol(asyncio.SubprocessProtocol):
    def __init__(self, done_future):
        super().__init__()
        self._done_future = done_future

    def pipe_data_received(self, fd, data):
        print("Received:", len(data))

    def process_exited(self):
        print("PROCESS EXITED!")
        self._done_future.set_result(None)

def run(loop):
    done_future = asyncio.Future(loop = loop)
    transport = None
    try:
        transport, protocol = yield from loop.subprocess_exec(
            lambda : MyProtocol(done_future),
            "ls",
            "-lh",
            stdin = None
        )
        yield from done_future
    finally:
        if transport: transport.close()

    return done_future.result()

def run_loop():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop) # bind event loop to current thread

    try: …
Run Code Online (Sandbox Code Playgroud)

python linux asynchronous python-3.x python-asyncio

6
推荐指数
1
解决办法
1373
查看次数

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
查看次数

标签 统计

python ×2

python-3.x ×2

python-asyncio ×2

asynchronous ×1

flask ×1

linux ×1