PyCharm导入模块出现未解析引用红线但代码可运行,如何解决?
It’s common for PyCharm’s code analysis to get out of sync with how Python actually runs your script, even when everything works at execution time. Here are a few straightforward ways to eliminate those red lines:
Solution 1: Use the Proper Relative Import (Recommended)
The cleanest approach is to adjust your import statement to match your project’s actual package structure. In test.py, replace:
from module import func1
with:
from package.module import func1
This follows standard Python packaging conventions, and PyCharm will immediately recognize the path once you make the change—no extra setup needed.
Solution 2: Mark the package Directory as a Sources Root
If you want to keep your original import statement, tell PyCharm to treat the package folder as a source directory (so it looks there for modules):
- Right-click on the
packagefolder in PyCharm’s Project sidebar - Hover over Mark Directory as
- Select Sources Root
The folder will turn blue, and PyCharm will stop flaggingmoduleandfunc1as unresolved references.
Solution 3: Add the package Directory to Your Interpreter’s Path
Another option is to manually add the package folder to PyCharm’s list of paths for your Python interpreter:
- Go to File > Settings > Project: [Your Project Name] > Python Interpreter
- Click the gear icon next to your interpreter, then select Show All
- Choose your active interpreter, then click the folder-with-arrow icon labeled Show paths for the selected interpreter
- Click the
+button, navigate to your project’spackagedirectory, and add it - Save your changes by clicking OK in all open windows. PyCharm will now include this directory when resolving imports.
Even though your script runs fine now, using Solution 1 is the best practice—it ensures your code works consistently across different environments and follows Python’s packaging rules.
内容的提问来源于stack exchange,提问作者Erel Segal-Halevi




