本地Streamlit应用启动时出现ModuleNotFoundError:找不到'app'模块的解决方法
本地Streamlit应用启动时出现ModuleNotFoundError:找不到'app'模块的解决方法
嗨,我看了你的问题和代码,这个模块找不到的问题其实是Python路径加载顺序和工作目录导致的,咱们一步步来解决:
问题根源
你在ui/streamlit_ui.py里先写了from app.model_loader import load_model,然后才添加项目根目录到Python路径——但Python是从上到下执行代码的,导入模块的时候根目录还没被加到路径里,自然找不到app模块;另外Streamlit启动时的工作目录可能不是你的项目根,也会影响模块识别。
方案1:调整streamlit_ui.py的代码顺序(最快解决)
把添加路径的代码移到所有import语句之前,这样Python在导入app模块前就已经知道项目根目录了:
import os import sys # 先把项目根目录添加到Python路径 sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) # 现在再导入其他模块 import streamlit as st from app.model_loader import load_model from app.analyzer import analyze_code print("Current working directory:", os.getcwd()) print("SRC Directory exists:", os.path.exists(os.path.join(os.path.dirname(__file__), "..", "src"))) # 后面的代码保持不变...
方案2:直接从项目根目录启动Streamlit
跳过main.py,直接在你的项目根目录(也就是D:\Gen AI projs\Code Analyzer)下执行命令:
(venv) D:\Gen AI projs\Code Analyzer>streamlit run ui/streamlit_ui.py
这样Streamlit启动时的工作目录就是项目根,Python会自动识别根目录下的app文件夹作为合法模块,不需要额外配置路径。
方案3:优化main.py的启动逻辑
如果你想继续用main.py启动,可以修改start_streamlit函数,让subprocess在项目根目录下运行Streamlit:
def start_streamlit(): """Starts the Streamlit application.""" try: logging.info("Starting Streamlit app...") # 获取项目根目录的绝对路径 project_root = os.path.dirname(os.path.abspath(__file__)) # 切换到项目根目录再启动Streamlit subprocess.run(["streamlit", "run", "ui/streamlit_ui.py"], cwd=project_root) except Exception as e: logging.error(f"Error starting Streamlit app: {e}")
额外建议
可以在app文件夹里创建一个空的__init__.py文件,让Python更明确地把它识别为一个可导入的模块——这是Python模块的规范写法,虽然现在可能不是必须的,但能避免一些潜在的路径问题。
备注:内容来源于stack exchange,提问作者Mohammed Saim Quadri




