Flask导入失败求助:执行python -c 'import flask'报错,昨日还正常如何解决?
Hey there, sorry to hear you're stuck with this Flask import issue—especially since it was working fine yesterday! Let's walk through the most common fixes step by step:
It's super easy to accidentally slip out of your project's virtual environment without noticing. If you're using a venv (which is best practice for Flask projects), first make sure it's activated:
- On Windows: Run
venv\Scripts\activatein your terminal - On macOS/Linux: Run
source venv/bin/activate
Once activated, test the import again withpython -c 'import flask'. If this works, you just forgot to activate the venv when working on your project today!
Your system might have multiple Python versions installed (like Python 3.9 vs 3.11), and Flask could be installed for one but not the other. Let's confirm:
- Run
which python(macOS/Linux) orwhere python(Windows) to see which Python path your terminal is using - Run
pip list | grep Flask(macOS/Linux) orpip list | findstr Flask(Windows) to check if Flask is installed for that version
If Flask isn't listed, install it explicitly for your current Python withpython -m pip install flask(usepython3instead ofpythonif needed).
Sometimes packages can get corrupted overnight (maybe a partial update or filesystem glitch). Uninstall and reinstall Flask to rule this out:
- Uninstall:
pip uninstall -y flask - Reinstall:
pip install flask
Test the import again withpython -c 'import flask'after this.
flask.py file This is a classic gotcha! If you accidentally created a file named flask.py in your project directory, Python will try to import that local file instead of the actual Flask package. Check your project folder for any files named flask.py (or flask.pyc) and rename or delete them immediately.
If Flask is installed but still not found, your PYTHONPATH might not include the directory where Flask is stored. Here's how to check:
- Run
python -c "import sys; print(sys.path)"to see all paths Python checks for packages - Find Flask's install location with
pip show flask | grep Location
If that location isn't in your sys.path, add it temporarily:- macOS/Linux:
export PYTHONPATH=$PYTHONPATH:/path/to/flask/location - Windows:
set PYTHONPATH=%PYTHONPATH%;C:\path\to\flask\location
Test the import again after updating the path.
- macOS/Linux:
If none of these steps work, feel free to share the exact error message you're getting—I can help dig deeper!
内容的提问来源于stack exchange,提问作者Evgeniya Tveritinova

