在CMD中运行Flask Shell时出现ModuleNotFoundError: No module named 'main'的原因排查求助
Let's break down why you're hitting this error and how to fix it step by step:
1. Incorrect Import Path in app/__init__.py
Your current import line from main import main_blueprint assumes main is a top-level Python module, but in your project structure, main is a sub-package nested inside the app directory. This mismatch is the root cause of the module not found error.
To fix this, use one of these valid import styles:
- Relative import (best for intra-package references, since we're importing from a sibling module within the
apppackage):from .main import main_blueprint - Absolute import (works if your project root is added to Python's system path):
from app.main import main_blueprint
2. Python Path & FLASK_APP Environment Variable Misconfiguration
When running flask shell, Flask needs to locate your application package correctly. If your project root directory isn't in Python's sys.path, it can't resolve the app.main module properly.
Fix steps:
- First, make sure you're running the
flask shellcommand from your project root directory (the folder containingapp/,static/, andtemplates/). - Set the
FLASK_APPenvironment variable to point to yourapppackage:- On Windows CMD:
set FLASK_APP=app - On Linux/macOS:
export FLASK_APP=app
- On Windows CMD:
- Run
flask shellagain after setting the variable.
3. Double-check Blueprint Registration (Optional but Critical)
While this isn't the direct cause of your current error, once you fix the import, ensure you're registering the blueprint in your app/__init__.py (either directly or in an app factory):
from flask import Flask from .main import main_blueprint # If not using an app factory app = Flask(__name__) app.register_blueprint(main_blueprint) # If using an app factory (recommended for larger apps) def create_app(): app = Flask(__name__) app.register_blueprint(main_blueprint) # Add other configs, extensions here return app
内容的提问来源于stack exchange,提问作者Aritra Mandal

