如何避免出现“ ValueError:找不到分隔符,并且块超出限制”

时间:2019-04-01 14:20:29

标签: python-3.x python-asyncio

我有一台以以下方式使用asyncio的服务器:

proc = await asyncio.subprocess.create_subprocess_exec(
    command,
    stdout=asyncio.subprocess.PIPE, 
    stderr=asyncio.subprocess.STDOUT)

async for line in proc.stdout:
    line = line.decode('utf-8').strip()
    print(line)

问题是,如果proc.stdout包含的行太长,我会在“ for”行中收到一条错误消息:

ValueError: Separator is not found, and chunk exceed the limit

如何才能检测到如此长的行,以免提前避免此错误?

1 个答案:

答案 0 :(得分:1)

documentation说:

  

limit参数为StreamReader包装器设置缓冲区限制   Process.stdoutProcess.stderr(如果将subprocess.PIPE传递给   stdout和stderr参数)。

似乎是我们所需要的。

默认限制seems to be 64 KiB,您可以尝试更高的方法:

proc = await asyncio.subprocess.create_subprocess_exec(
    command,
    limit = 1024 * 128,  # 128 KiB
    stdout=asyncio.subprocess.PIPE, 
    stderr=asyncio.subprocess.STDOUT)

更新:

  

我只想截断/忽略太长的行。这是   可能吗?

您可以消除长行错误,然后继续。以下代码(在Windows上经过测试)显示了这个想法:

import asyncio


async def main():
    proc = await asyncio.subprocess.create_subprocess_exec(
        *[
            'wget', 
            '--help'
        ],
        limit = 20,
        stdout=asyncio.subprocess.PIPE, 
        stderr=asyncio.subprocess.STDOUT)

    while True:
        try:
            async for line in proc.stdout:
                line = line.decode('utf-8').strip()
                print(line)
        except ValueError:
            continue
        else:
            break


loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(loop)
loop.run_until_complete(main())