我有一个目录结构
├── simulate.py
├── src
│ ├── networkAlgorithm.py
│ ├── ...
我可以使用sys.path.insert()访问网络模块。
import sys
import os.path
sys.path.insert(0, "./src")
from networkAlgorithm import *
但是,pycharm抱怨它无法访问该模块。我如何教pycham解决引用?
我有一个目录结构
├── simulate.py
├── src
│ ├── networkAlgorithm.py
│ ├── ...
我可以使用sys.path.insert()访问网络模块。
import sys
import os.path
sys.path.insert(0, "./src")
from networkAlgorithm import *
但是,pycharm抱怨它无法访问该模块。我如何教pycham解决引用?
当前回答
在PyCharm 2019.3.1中完成 右键单击src文件夹->“标记目录为”->单击“排除”,您的src文件夹应该是蓝色的。
其他回答
在新版本的pycharm中,只需右键单击想要导入文件的目录或python包,然后单击“标记目录为”->“源根”
对于我来说:
Directory0
├── Directory1
│ └── file1.py
├── Directory2
│ ├── file2.py
在file1中,我有:
from Directory2 import file2
它传输一个“未解决的引用Directory2”。
我是这样解决的:
如上所述,将父目录Directory0标记为“源根”
AND
把我的光标放在我有错误的文件上的另一行,这样它就会考虑到我的修改
这很愚蠢,但如果我不执行第二个操作,错误仍然会出现,并可能使您认为您没有通过将父目录标记为Source Root来解决问题。
我也有同样的问题,也尝试了很多建议,但没有一个有效,直到我发现了这篇文章(https://stackoverflow.com/a/62632870/16863617)。尽管他的解决方案对我不起作用,但它帮助我想出了将_init.py_添加到——>设置|编辑器|文件类型| Python |注册模式的想法
截图
未解决的引用错误现在已经解决。
这里所有的东西我都试过两次,甚至更多。我最终解决了这个问题,做了一些我在网上从未见过的事情。如果你去>编辑器>文件类型的设置,在底部有一个“忽略文件和文件夹”行。在我的例子中,我忽略了“venv”,这是我的虚拟环境的名字。所以我去掉了venv;从目录列表中忽略,瞧!!我终于解决了这个问题。实际上,我在这个项目中遇到的所有导入问题都得到了解决。
BTW, I had installed each and every package using PyCharm, and not through a terminal. (Meaning, by going to Settings>Interpreter...). I had invalidated cache, changed 'Source Root', restarted PyCharm, refreshed my interpreters paths, changed interpreters, deleted my venv... I tried everything. This finally worked. Obviously there are multiple problems going on here with different people, so this may not work for you, but it's definitely worth a shot if nothing else has worked, and easy to reverse if it doesn't.
通常,$PYTHONPATH用于教python解释器查找必要的模块。PyCharm需要在Preference中添加路径。