python - Python Websocket 模块继续启动不会被杀死导致内存问题的进程
问题描述
我有这段代码在用于分割音频文件的服务器上运行。我正在使用 websockets 来触发浏览器。
问题是这个拆分过程的每个触发器都会创建 10 个新的 python 进程,这些进程在运行一段时间后不会被杀死,从而导致内存错误。我无法弄清楚为什么要创建这些流程以及如何改进脚本。现在我正在使用一种每天运行一次的 cron 作业的 hacky 方法来杀死任何剩余的进程。任何关于这些进程的作用或创建它们的原因以及在脚本运行后如何自动杀死它们的任何指针都会很棒。
编码:
#!/usr/bin/env python
import websockets
#import aiohttp
import asyncio
from pathlib import Path
from io import BytesIO
from spleeter.separator import Separator
import sys
import tempfile
import os
from zipfile import ZipFile
async def split(websocket, path):
print("split started")
stems = await websocket.recv()
audioFormat = await websocket.recv()
bitRate = await websocket.recv()
audio_bytes = await websocket.recv()
separator = Separator('spleeter:'+stems+'stems')
temp, pathname = tempfile.mkstemp()
file_paths = []
p = Path('/tmp/filename/'+str(pathname).split('/')[2])
if not (os.path.exists(p)):
print('New Path')
with open(pathname, mode='wb') as f:
f.write(audio_bytes)
print('Writing to file ' + str(f) + 'with seperator: ' + str(separator))
if audioFormat == "mp3":
print("mp3")
separator.separate_to_file(pathname, "/tmp/filename", codec="mp3", bitrate=bitRate)
else:
print("wav")
separator.separate_to_file(pathname, "/tmp/filename")
separator.join()
print('Separating finished')
oldwd = os.getcwd()
os.chdir(p)
for entry in os.scandir(path='.'):
print('Appending file: ' + str(entry))
if entry.is_file():
file_paths.append(entry)
with ZipFile(p / 'files.zip','w') as zip:
for f in file_paths:
zip.write(f)
print('Zip created')
os.chdir(oldwd)
f=open(p / 'files.zip', "rb")
contents = f.read()
await websocket.send(contents)
print('Zip sent to client')
async def main():
print("main called")
async with websockets.serve(
split,
# "0.0.0.0",
"localhost",
9014,
max_size = None,
create_protocol=websockets.basic_auth_protocol_factory(
realm="my dev server",
credentials=("TEST", "CREDS"),
)
):
await asyncio.Future() # run forever
asyncio.run(main())
解决方案
我假设您应该在 split 函数中针对 websocket 参数使用上下文管理器,就像文档中的 hello 函数一样:https ://websockets.readthedocs.io/en/stable/