- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试运行 Subprocess在 FastApi 路由中,但执行结果出现 NotImplementedError
。我读过有关此问题的类似问题:
Why am I getting NotImplementedError with async and await on Windows?
Asyncio.create_subprocess_exec NotImplementedError - Fastapi Background Task
但他们似乎没有任何可行的解决方案。
我的 FastApi 路线如下所示:
@app.get("/test/subprocess")
async def subprocess_test():
parsed_json = await(probe_video_file(Path(r"G:\ffmpeg testing\ffmpeg\ffprobe.exe"),
Path(r"G:\ffmpeg testing\input_file\test_file.wmv")))
print(parsed_json)
return parsed_json
当我导航到此路线时,会引发异常并且代码崩溃。probe_video_file
函数内部有一个子进程调用,如下所示:
async def probe_video_file(ffprobe_path: Path, file_to_probe: Path) -> dict:
"""
Probes a video file with FFprobe.
:param ffprobe_path: Path to ffprobe executable
:param file_to_probe: Path to file to probe
:returns Parsed JSON dict of the output
"""
args = [f'{str(ffprobe_path)}', f'{str(file_to_probe)}']
args += ["-hide_banner", "-loglevel", "fatal", "-show_error", "-show_format", "-show_streams", "-show_chapters",
"-show_private_data", "-print_format", "json"]
#sub process is here, and here is where the exception happens.
proc = await asyncio.create_subprocess_exec(
*args,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
stdout, stderr = await proc.communicate()
print(f'exited with {proc.returncode}]')
if stdout:
print(f'[stdout]\n{stdout.decode()}')
if stderr:
print(f'[stderr]\n{stderr.decode()}')
raise Exception(f"Failed to probe file {file_to_probe}")
return json.loads(stdout)
当我在没有 FastAPI 的情况下运行 probe_video_file
时,如下所示:
async def main():
json_output = await probe_video_file(Path(r"G:\ffmpeg testing\ffmpeg\ffprobe.exe"),
Path(r"G:\ffmpeg testing\input_file\test_file.wmv"))
print(json_output)
if __name__ == '__main__':
asyncio.run(main())
它运行良好并打印正确的输出:
[['G:\\ffmpeg testing\\ffmpeg\\ffprobe.exe', 'G:\\ffmpeg testing\\input_file\\test_file.wmv', '-hide_banner', '-loglevel', 'fatal', '-show_error', '-show_format', '-show_streams', '-show_chapters', '-show_private_data', '-print_format', 'json'] exited with 0]
[stdout]
{
"streams": [
{
"index": 0,
"codec_name": "wmav2",
"codec_long_name": "Windows Media Audio 2",
"codec_type": "audio",
"codec_tag_string": "a[1][0][0]",
"codec_tag": "0x0161",
"sample_fmt": "fltp",
"sample_rate": "48000",
"channels": 2,
"bits_per_sample": 0,
"r_frame_rate": "0/0",
"avg_frame_rate": "0/0",
"time_base": "1/1000",
"start_pts": 0,
"start_time": "0.000000",
"duration_ts": 2155050,
"duration": "2155.050000",
"bit_rate": "96000",
"disposition": {
"default": 0,
"dub": 0,
"original": 0,
"comment": 0,
"lyrics": 0,
"karaoke": 0,
"forced": 0,
"hearing_impaired": 0,
"visual_impaired": 0,
"clean_effects": 0,
"attached_pic": 0,
"timed_thumbnails": 0
},
"tags": {
"language": "eng"
}
},
{
"index": 1,
"codec_name": "wmv3",
"codec_long_name": "Windows Media Video 9",
"profile": "Main",
"codec_type": "video",
"codec_tag_string": "WMV3",
"codec_tag": "0x33564d57",
"width": 850,
"height": 480,
"coded_width": 850,
"coded_height": 480,
"closed_captions": 0,
"has_b_frames": 0,
"pix_fmt": "yuv420p",
"level": -99,
"chroma_location": "left",
"refs": 1,
"r_frame_rate": "30000/1001",
"avg_frame_rate": "30000/1001",
"time_base": "1/1000",
"start_pts": 0,
"start_time": "0.000000",
"duration_ts": 2155050,
"duration": "2155.050000",
"bit_rate": "2000000",
"disposition": {
"default": 0,
"dub": 0,
"original": 0,
"comment": 0,
"lyrics": 0,
"karaoke": 0,
"forced": 0,
"hearing_impaired": 0,
"visual_impaired": 0,
"clean_effects": 0,
"attached_pic": 0,
"timed_thumbnails": 0
},
"tags": {
"language": "eng"
}
}
],
"chapters": [
],
"format": {
"filename": "G:\\ffmpeg testing\\input_file\\test_file.wmv",
"nb_streams": 2,
"nb_programs": 0,
"format_name": "asf",
"format_long_name": "ASF (Advanced / Active Streaming Format)",
"start_time": "0.000000",
"duration": "2155.050000",
"size": "567194391",
"bit_rate": "2105545",
"probe_score": 100,
"tags": {
"WMFSDKNeeded": "0.0.0.0000",
"DeviceConformanceTemplate": "MP@HL",
"WMFSDKVersion": "11.0.5721.5265",
"IsVBR": "0"
}
}
}
{'streams': [{'index': 0, 'codec_name': 'wmav2', 'codec_long_name': 'Windows Media Audio 2', 'codec_type': 'audio', 'codec_tag_string': 'a[1][0][0]', 'codec_tag': '0x0161', 'sample_fmt': 'fltp', 'sample_rate': '48000', 'channels': 2, 'bits_per_sample': 0, 'r_frame_rate': '0/0', 'avg_frame_rate': '0/0', 'time_base': '1/1000', 'start_pts': 0, 'start_time': '0.000000', 'duration_ts': 2155050, 'duration': '2155.050000', 'bit_rate': '96000', 'disposition': {'default': 0, 'dub': 0, 'original': 0, 'comment': 0, 'lyrics': 0, 'karaoke': 0, 'forced': 0, 'hearing_impaired': 0, 'visual_impaired': 0, 'clean_effects': 0, 'attached_pic': 0, 'timed_thumbnails': 0}, 'tags': {'language': 'eng'}}, {'index': 1, 'codec_name': 'wmv3', 'codec_long_name': 'Windows Media Video 9', 'profile': 'Main', 'codec_type': 'video', 'codec_tag_string': 'WMV3', 'codec_tag': '0x33564d57', 'width': 850, 'height': 480, 'coded_width': 850, 'coded_height': 480, 'closed_captions': 0, 'has_b_frames': 0, 'pix_fmt': 'yuv420p', 'level': -99, 'chroma_location': 'left', 'refs': 1, 'r_frame_rate': '30000/1001', 'avg_frame_rate': '30000/1001', 'time_base': '1/1000', 'start_pts': 0, 'start_time': '0.000000', 'duration_ts': 2155050, 'duration': '2155.050000', 'bit_rate': '2000000', 'disposition': {'default': 0, 'dub': 0, 'original': 0, 'comment': 0, 'lyrics': 0, 'karaoke': 0, 'forced': 0, 'hearing_impaired': 0, 'visual_impaired': 0, 'clean_effects': 0, 'attached_pic': 0, 'timed_thumbnails': 0}, 'tags': {'language': 'eng'}}], 'chapters': [], 'format': {'filename': 'G:\\ffmpeg testing\\input_file\\test_file.wmv', 'nb_streams': 2, 'nb_programs': 0, 'format_name': 'asf', 'format_long_name': 'ASF (Advanced / Active Streaming Format)', 'start_time': '0.000000', 'duration': '2155.050000', 'size': '567194391', 'bit_rate': '2105545', 'probe_score': 100, 'tags': {'WMFSDKNeeded': '0.0.0.0000', 'DeviceConformanceTemplate': 'MP@HL', 'WMFSDKVersion': '11.0.5721.5265', 'IsVBR': '0'}}}
Process finished with exit code 0
我已经尝试将事件循环“设置”为 ProactorEventLoop
,就像其他问题中建议的那样:
@app.on_event("startup")
async def startup_event():
"""Code runs at startup..."""
loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(loop)
但是没有效果。
这是异常回溯:
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "E:\pycharm\my_project\venv\lib\site-packages\uvicorn\protocols\http\httptools_impl.py", line 375, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "E:\pycharm\my_project\venv\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 75, in __call__
return await self.app(scope, receive, send)
File "E:\pycharm\my_project\venv\lib\site-packages\fastapi\applications.py", line 208, in __call__
await super().__call__(scope, receive, send)
File "E:\pycharm\my_project\venv\lib\site-packages\starlette\applications.py", line 112, in __call__
await self.middleware_stack(scope, receive, send)
File "E:\pycharm\my_project\venv\lib\site-packages\starlette\middleware\errors.py", line 181, in __call__
raise exc
File "E:\pycharm\my_project\venv\lib\site-packages\starlette\middleware\errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "E:\pycharm\my_project\venv\lib\site-packages\starlette\middleware\cors.py", line 84, in __call__
await self.app(scope, receive, send)
File "E:\pycharm\my_project\venv\lib\site-packages\starlette\exceptions.py", line 82, in __call__
raise exc
File "E:\pycharm\my_project\venv\lib\site-packages\starlette\exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "E:\pycharm\my_project\venv\lib\site-packages\starlette\routing.py", line 656, in __call__
await route.handle(scope, receive, send)
File "E:\pycharm\my_project\venv\lib\site-packages\starlette\routing.py", line 259, in handle
await self.app(scope, receive, send)
File "E:\pycharm\my_project\venv\lib\site-packages\starlette\routing.py", line 61, in app
response = await func(request)
File "E:\pycharm\my_project\venv\lib\site-packages\fastapi\routing.py", line 226, in app
raw_response = await run_endpoint_function(
File "E:\pycharm\my_project\venv\lib\site-packages\fastapi\routing.py", line 159, in run_endpoint_function
return await dependant.call(**values)
File "E:\pycharm\my_project\src\backend\app\api\api.py", line 202, in subprocess_test
parsed_json = await(probe_video_file(Path(r"G:\ffmpeg testing\ffmpeg\ffprobe.exe"),
File "E:\pycharm\my_project\src\backend\app\ffmpeg\ffprobe.py", line 26, in probe_video_file
proc = await asyncio.create_subprocess_exec(
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\asyncio\subprocess.py", line 218, in create_subprocess_exec
transport, protocol = await loop.subprocess_exec(
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 1652, in subprocess_exec
transport = await self._make_subprocess_transport(
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 493, in _make_subprocess_transport
raise NotImplementedError
NotImplementedError
INFO: 127.0.0.1:58576 - "GET /test/subprocess HTTP/1.1" 500 Internal Server Error
有谁知道怎么解决吗?据我了解,这与 FastApi 的默认事件循环不支持此有关。但我不知道如何使用 Asyncio 的默认事件循环设置或替换默认的 FastApi 事件循环。
我认为有必要指出我正在使用 Windows 10。
最佳答案
仔细看看 uvicorn 代码,似乎 reload=True
选项导致默认的 ProactorEventLoop
更改为 SelectorEventLoop
在 window 上。您可以在不使用 reload=True
的情况下尝试一下,看看它是否有效(我现在无法测试它)。但是,如果您需要在 uvicorn 中强制使用特定事件循环,您可以像这样子类化 uvicorn.Server
:
import asyncio
from asyncio.windows_events import ProactorEventLoop
from fastapi import FastAPI
from uvicorn import Config, Server
app = FastAPI()
class ProactorServer(Server):
def run(self, sockets=None):
loop = ProactorEventLoop()
asyncio.set_event_loop(loop) # since this is the default in Python 3.10, explicit selection can also be omitted
asyncio.run(self.serve(sockets=sockets))
config = Config(app=app, host="0.0.0.0", port=8000, reload=True)
server = ProactorServer(config=config)
server.run()
这应该允许您在 FastAPI 端点中使用 asyncio.create_subprocess_exec()
。
关于python - 在 FastApi 中运行 Asyncio 子进程会导致 NotImplementedError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70568070/
我需要将文本放在 中在一个 Div 中,在另一个 Div 中,在另一个 Div 中。所以这是它的样子: #document Change PIN
奇怪的事情发生了。 我有一个基本的 html 代码。 html,头部, body 。(因为我收到了一些反对票,这里是完整的代码) 这是我的CSS: html { backgroun
我正在尝试将 Assets 中的一组图像加载到 UICollectionview 中存在的 ImageView 中,但每当我运行应用程序时它都会显示错误。而且也没有显示图像。 我在ViewDidLoa
我需要根据带参数的 perl 脚本的输出更改一些环境变量。在 tcsh 中,我可以使用别名命令来评估 perl 脚本的输出。 tcsh: alias setsdk 'eval `/localhome/
我使用 Windows 身份验证创建了一个新的 Blazor(服务器端)应用程序,并使用 IIS Express 运行它。它将显示一条消息“Hello Domain\User!”来自右上方的以下 Ra
这是我的方法 void login(Event event);我想知道 Kotlin 中应该如何 最佳答案 在 Kotlin 中通配符运算符是 * 。它指示编译器它是未知的,但一旦知道,就不会有其他类
看下面的代码 for story in book if story.title.length < 140 - var story
我正在尝试用 C 语言学习字符串处理。我写了一个程序,它存储了一些音乐轨道,并帮助用户检查他/她想到的歌曲是否存在于存储的轨道中。这是通过要求用户输入一串字符来完成的。然后程序使用 strstr()
我正在学习 sscanf 并遇到如下格式字符串: sscanf("%[^:]:%[^*=]%*[*=]%n",a,b,&c); 我理解 %[^:] 部分意味着扫描直到遇到 ':' 并将其分配给 a。:
def char_check(x,y): if (str(x) in y or x.find(y) > -1) or (str(y) in x or y.find(x) > -1):
我有一种情况,我想将文本文件中的现有行包含到一个新 block 中。 line 1 line 2 line in block line 3 line 4 应该变成 line 1 line 2 line
我有一个新项目,我正在尝试设置 Django 调试工具栏。首先,我尝试了快速设置,它只涉及将 'debug_toolbar' 添加到我的已安装应用程序列表中。有了这个,当我转到我的根 URL 时,调试
在 Matlab 中,如果我有一个函数 f,例如签名是 f(a,b,c),我可以创建一个只有一个变量 b 的函数,它将使用固定的 a=a1 和 c=c1 调用 f: g = @(b) f(a1, b,
我不明白为什么 ForEach 中的元素之间有多余的垂直间距在 VStack 里面在 ScrollView 里面使用 GeometryReader 时渲染自定义水平分隔线。 Scrol
我想知道,是否有关于何时使用 session 和 cookie 的指南或最佳实践? 什么应该和什么不应该存储在其中?谢谢! 最佳答案 这些文档很好地了解了 session cookie 的安全问题以及
我在 scipy/numpy 中有一个 Nx3 矩阵,我想用它制作一个 3 维条形图,其中 X 轴和 Y 轴由矩阵的第一列和第二列的值、高度确定每个条形的 是矩阵中的第三列,条形的数量由 N 确定。
假设我用两种不同的方式初始化信号量 sem_init(&randomsem,0,1) sem_init(&randomsem,0,0) 现在, sem_wait(&randomsem) 在这两种情况下
我怀疑该值如何存储在“WORD”中,因为 PStr 包含实际输出。? 既然Pstr中存储的是小写到大写的字母,那么在printf中如何将其给出为“WORD”。有人可以吗?解释一下? #include
我有一个 3x3 数组: var my_array = [[0,1,2], [3,4,5], [6,7,8]]; 并想获得它的第一个 2
我意识到您可以使用如下方式轻松检查焦点: var hasFocus = true; $(window).blur(function(){ hasFocus = false; }); $(win
我是一名优秀的程序员,十分优秀!