本文翻译自:Unresolved reference issue in PyCharm
I have a directory structure 我有一个目录结构
├── simulate.py
├── src
│ ├── networkAlgorithm.py
│ ├── ...
And I can access the network module with sys.path.insert()
. 而且我可以使用sys.path.insert()
访问网络模块。
import sys
import os.path
sys.path.insert(0, "./src")
from networkAlgorithm import *
However, pycharm complains that it cannot access the module. 但是,pycharm抱怨它无法访问该模块。 How can I teach pycham to resolve the reference? 我如何教pycham解析参考文献?
#1楼
参考:https://stackoom.com/question/1R6fQ/PyCharm中未解决的参考问题
#2楼
Normally, $PYTHONPATH is used to teach python interpreter to find necessary modules . 通常, $ PYTHONPATH用于教python解释器查找必要的模块 。 PyCharm needs to add the path in Preference. PyCharm需要在“首选项”中添加路径。
#3楼
Manually adding it as you have done is indeed one way of doing this, but there is a simpler method, and that is by simply telling pycharm that you want to add the src
folder as a source root, and then adding the sources root to your python path. 手动将其添加为你所做的确实是这样做的一种方式,但有一个简单的方法,那就是通过简单地告诉pycharm要添加src
文件夹作为源根目录,然后添加源根到您的python路径。
This way, you don't have to hard code things into your interpreter's settings: 这样,您就不必将代码硬编码到解释器的设置中:
- Add
src
as a source content root: 将src
添加为源内容根:
- Then make sure to add add sources to your
PYTHONPATH
: 然后确保将添加源添加到您的PYTHONPATH
:
- Now imports will be resolved: 现在将解决进口问题:
This way, you can add whatever you want as a source root, and things will simply work. 这样,您可以将任何所需的内容添加为源根,一切将简单地进行。 If you unmarked it as a source root however, you will get an error: 但是,如果未将其标记为源根, 则会出现错误:
#4楼
Many a times what happens is that the plugin is not installed. 很多时候发生的事情是没有安装插件。 eg 例如
If you are developing a django project and you do not have django plugin installed in pyCharm, it says error 'unresolved reference'. 如果您正在开发django项目,并且在pyCharm中未安装django插件,则会显示错误“未解决的引用”。 Refer: https://www.jetbrains.com/pycharm/help/resolving-references.html 请参阅: https : //www.jetbrains.com/pycharm/help/resolving-references.html
#5楼
Please check if you are using the right interpreter that you are supposed to. 请检查您是否使用了正确的解释器。 I was getting error "unresolved reference 'django' " to solve this I changed Project Interpreter (Changed Python 3 to Python 2.7) from project settings: Select Project, go to File -> Settings -> Project: -> Project Interpreter -> Brows and Select correct version or Interpreter (eg /usr/bin/python2.7). 我收到错误消息“未解决的参考'django'”以解决此问题,我从项目设置中更改了项目解释器(将Python 3更改为Python 2.7):选择项目,转到文件->设置->项目:->项目解释器->浏览并选择正确的版本或解释器(例如/usr/bin/python2.7)。
#6楼
After testing all workarounds, i suggest you to take a look at Settings -> Project -> project dependencies
and re-arrange them. 测试完所有解决方法后,建议您查看Settings -> Project -> project dependencies
然后重新排列它们。