From 668785ebe53c201ef8c503892cf31b513b1465e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E5=BB=BA=E6=AD=A6?= Date: Fri, 9 May 2025 11:57:11 +0800 Subject: [PATCH] =?UTF-8?q?refactor(path=5Fhelper):=20=E9=87=8D=E6=9E=84?= =?UTF-8?q?=E8=B7=AF=E5=BE=84=E8=8E=B7=E5=8F=96=E6=96=B9=E6=B3=95=EF=BC=8C?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E6=89=93=E5=8C=85=E8=BF=90=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 修改 get_data_dir 函数,以支持打包后可写的运行目录- 新增 get_app_dir 函数,提供更灵活的路径获取方式 - 优化路径处理逻辑,确保在不同环境下都能正确获取路径 --- backend/app/utils/path_helper.py | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/backend/app/utils/path_helper.py b/backend/app/utils/path_helper.py index 9a9e44e..4ca28dd 100644 --- a/backend/app/utils/path_helper.py +++ b/backend/app/utils/path_helper.py @@ -6,7 +6,14 @@ PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../") def get_data_dir(): - data_path = os.path.join(PROJECT_ROOT, "data") + if getattr(sys, 'frozen', False): + # ✅ 打包后使用可写的运行目录 + base_dir = os.path.dirname(sys.executable) + else: + # ✅ 开发时使用项目根目录下的 data 目录 + base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../data")) + + data_path = os.path.join(base_dir, "data") os.makedirs(data_path, exist_ok=True) return data_path @@ -24,3 +31,20 @@ def get_model_dir(subdir: str = "whisper") -> str: os.makedirs(path, exist_ok=True) return path + +def get_app_dir(subdir: str = "") -> str: + """ + 返回一个稳定的可写目录: + - 开发时:使用项目 data 目录 + - 打包后:使用 exe 所在目录 + """ + if getattr(sys, 'frozen', False): + # 打包后运行:使用 main.exe 所在目录 + base_dir = os.path.dirname(sys.executable) + else: + # 开发模式:使用项目的 /data 目录 + base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../data")) + + full_path = os.path.join(base_dir, subdir) + os.makedirs(full_path, exist_ok=True) + return full_path \ No newline at end of file