You need to enable JavaScript to run this app. 如何修复为Popen.stdout.readline设置asyncio超时出现的类型错误问题
优惠活动
大模型
产品
解决方案
定价
更多

如何修复为Popen.stdout.readline设置asyncio超时出现的类型错误问题

错误原因

你触发报错的根本原因是:subprocess.Popen返回的stdout是普通同步文件对象,它的readline()是同步阻塞方法,调用后直接返回字符串,不是asyncio要求的可等待对象(协程、Future等),所以传入asyncio.wait_for会触发类型错误。

修复方案

方案1(推荐):使用asyncio原生异步子进程接口

asyncio自带了异步实现的子进程创建接口asyncio.create_subprocess_shell,它返回的进程对象的stdout是异步流对象StreamReader,对应的readline()是可等待的协程,完美适配你的需求。

修改后的完整代码如下:

import asyncio

class collector():
    @staticmethod
    async def readline(proc, timeout=3):
        try:
            line = await asyncio.wait_for(proc.stdout.readline(), timeout)
        except asyncio.TimeoutError:
            return ""
        else:
            # 异步readline默认返回bytes,可根据需要转字符串
            return line.decode('utf-8', errors='ignore')

    @staticmethod
    async def background(command):
        # 使用asyncio原生异步子进程接口
        proc = await asyncio.create_subprocess_shell(
            command,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE
        )

        while True:
            line = await collector.readline(proc=proc, timeout=3)
            # 此处可添加自定义的行处理逻辑
            if line.strip():
                print(line.strip())
            # 进程退出后读到空内容终止循环
            if proc.returncode is not None and line == b'':
                break

asyncio.run(collector.background("tail -f /tmp/2222"))

方案2:兼容原有同步Popen的实现

如果你一定要保留原来的subprocess.Popen调用,可以用asyncio.to_thread(Python3.9+支持)把同步的readline操作包装成可等待对象:

import asyncio
import subprocess

class collector():
    @staticmethod
    async def readline(file, timeout=3):
        try:
            # 把同步readline操作放到独立线程执行,包装为可等待对象
            line = await asyncio.wait_for(
                asyncio.to_thread(file.stdout.readline),
                timeout
            )
        except asyncio.TimeoutError:
            return ""
        else:
            return line

    @staticmethod
    async def background(command):
        # text=True参数指定返回字符串而非bytes
        f = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

        while True:
            line = await collector.readline(file=f, timeout=3)

asyncio.run(collector.background("tail -f /tmp/2222"))

内容的提问来源于stack exchange,提问作者Zohar81

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 22:24:02