我希望能够在子进程stdout上设置超时时间,并在超时后返回一个空字符串。
这是使用asyncio的尝试,但在asyncio.wait_for中使用file.stdout.readline()失败了。
有什么好的解决方法吗?
这是使用asyncio的尝试,但在asyncio.wait_for中使用file.stdout.readline()失败了。
有什么好的解决方法吗?
import threading
import select
import subprocess
import queue
import time
import asyncio
class collector():
@staticmethod
async def readline(file, timeout=3):
try:
line = await asyncio.wait_for(file.stdout.readline(), timeout)
except asyncio.TimeoutError:
return ""
else:
return line
@staticmethod
async def background(command):
f = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while True:
line = await collector.readline(file=f, timeout=3)
asyncio.run(collector.background("tail -f /tmp/2222"))
下面是调用堆栈:
File "/tmp/script.py", line 13, in readline
line = await asyncio.wait_for(file.stdout.readline(), timeout)
File "/usr/local/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/tasks.py", line 462, in wait_for
fut = ensure_future(fut, loop=loop)
File "/usr/local/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/tasks.py", line 679, in ensure_future
raise TypeError('An asyncio.Future, a coroutine or an awaitable is '
TypeError: An asyncio.Future, a coroutine or an awaitable is required
file.stdout.readline()
将返回一行——一个str
或bytes
。你不能等待一个str
或bytes
——你已经拥有它了。 - MisterMiyagi