![](/img/trans.png)
[英]Asyncio.create_subprocess_exec NotImplementedError - Fastapi Background Task
[英]How to create my own pipe in asyncio.create_subprocess_exec
我有一個程序,我必須從網絡中提取文件(p4 print 從版本控制服務器中提取文件並打印到標准輸出)。 因為網絡和 IO 是最大的瓶頸,我正在嘗試使用 asyncio。 我嘗試使用標准的 asyncio.subprocess.PIPE,但由於我有多個子進程,我不斷遇到死鎖。 我想嘗試的解決方案是創建一個新文件並將標准輸出寫入那里。
這是我得到的一些錯誤
嘗試 2:錯誤“OSError:[Errno 9] 錯誤文件描述符”
async def _subprocess_wrapper(self, path):
async with self.sem:
_, write = os.pipe()
proc = await asyncio.create_subprocess_exec(
'p4', 'print', '-q', path,
stdout=write,
stderr=write
)
status = await proc.wait()
file = os.fdopen(write, 'r')
txt = file.read()
os.close(write)
os.close(_)
return status, txt
嘗試 3:錯誤“AttributeError: 'NoneType' object has no attribute 'read'”
async def _subprocess_wrapper(self, path):
async with self.sem:
_, write = os.pipe()
proc = await asyncio.create_subprocess_exec(
'p4', 'print', '-q', path,
stdout=write,
stderr=write
)
status = await proc.wait()
if status != 0:
txt = await proc.stderr.read()
else:
txt = await proc.stdout.read()
os.close(write)
os.close(_)
return status, txt.decode()
任何幫助,將不勝感激
根據文檔,我放棄了嘗試使用自己的 pipe 並更改了我的 wait() 進行通信...
[wait] 在使用 stdout=PIPE 或 stderr=PIPE 時可能會死鎖,並且子進程會生成如此多的 output 以至於它阻塞等待 OS pipe 緩沖區接受更多數據。 使用管道時使用communicate()方法來避免這種情況
我的工作代碼
async def _subprocess_wrapper(self, path):
async with self.sem:
proc = await asyncio.create_subprocess_exec(
'p4', 'print', '-q', path,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await proc.communicate()
txt = stdout if proc.returncode == 0 else stderr
return proc.returncode, txt.decode()
如果有人知道是否有更好的方法來制作這種規模,我將不勝感激
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.