0

我试图asyncio.create_subprocess_exec在 Fastapi 后台任务中调用,但它不断提高NotImplementedError. run_subprocess 函数在 Fastapi 之外运行时可以正常工作。我在 Windows 中使用 asyncio 循环而不是 uvloop 运行它。

import asyncio
from fastapi import FastAPI, BackgroundTasks

DHCP_SERVER = "1.1.1.1"

app = FastAPI()

@app.get("/")
async def subprocess_test(background_tasks: BackgroundTasks):
  background_tasks.add_task(run_subprocess)

async def run_subprocess():
  proc = await asyncio.create_subprocess_exec(
    'powershell.exe',
    f'Get-Dhcp-Serverv4Scope -ComputerName \"{DHCP_SERVER}\"',
    stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
  )

  stdout, stderr = await proc.communicate()

  if stderr:
    print(stderr)
  else:
    print(stdout)


File ".\subprocess_example.py", line 13 in run_subprocess
  proc = await asyncio.create_subprocess_exec(
File "C:\Python\Python38-32\lib\asyncio\subprocess.py", line 236, in create_subprcess_exec
  transport, protocol = await loop.subprocess_exec(
File "C:\Python\Python38-32\lib\asyncio\base_events.py", line 1615, in subprocess_exec
  transport = await self._make_subprocess_transport(
File "C:\Python\Python38-32\lib\asyncio\base_events.py", line 487, in _make_subprocess_transport
  raise NotImplementedError

任何人都可以帮忙解决这个问题吗?

谢谢!

4

1 回答 1

0

我相信这个错误是触发的,因为 fastapi 使用 uvloop 并且 asyncio 在没有设置策略的情况下不知道这一点,有一个答案提供了一些如何实现这一点的钩子;

与 uvloop 等效的异步事件循环

于 2020-02-05T19:24:49.760 回答