我有一台以以下方式使用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
如何才能检测到如此长的行,以免提前避免此错误?
答案 0 :(得分:1)
limit
参数为StreamReader
包装器设置缓冲区限制Process.stdout
和Process.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())