Unresolved reference issue in PyCharm

2019-01-02 16:46发布

I have a directory structure

├── simulate.py
├── src
│   ├── networkAlgorithm.py
│   ├── ...

And I can access the network module with 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. How can I teach pycham to resolve the reference?

enter image description here

11条回答
与君花间醉酒
2楼-- · 2019-01-02 17:03

Normally, $PYTHONPATH is used to teach python interpreter to find necessary modules. PyCharm needs to add the path in Preference.

enter image description here

查看更多
不流泪的眼
3楼-- · 2019-01-02 17:03

Install via PyCharm (works with Community Edition). Open up Settings > Project > Project Interpreter then click the green + icon in the screenshot below. In the 2nd dialogue that opens, enter the package name and click the 'Install Package' button.

enter image description here

查看更多
琉璃瓶的回忆
4楼-- · 2019-01-02 17:04

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 (e.g /usr/bin/python2.7).

查看更多
孤独寂梦人
5楼-- · 2019-01-02 17:07

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.

This way, you don't have to hard code things into your interpreter's settings:

  • Add src as a source content root:

                            enter image description here

  • Then make sure to add add sources to your PYTHONPATH:

enter image description here

  • Now imports will be resolved:

                      enter image description here

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:

                                  enter image description here

查看更多
伤终究还是伤i
6楼-- · 2019-01-02 17:07

If anyone is still looking at this, the accepted answer still works for PyCharm 2016.3 when I tried it. The UI might have changed, but the options are still the same.

ie. Right click on your root folder --> 'Mark Directory As' --> Source Root

查看更多
登录 后发表回答