Import directory into pycharm

2019-04-23 17:12发布

I am trying to import a legacy project into pycharm for debugging. The directory structure looks like:

top folder ---> folder one

top folder ---> folder two

The problem is that programs in the sub-folders use:

 import top 
 from top import module  

Pycharm returns the error: "No module named top"

How can I fix this?

2条回答
仙女界的扛把子
2楼-- · 2019-04-23 17:22

First thing to make sure is to do what Games said, you need to make sure each folder that is representing a package is done by putting a __init__.py file which is a empty python file named exactly __init__.py that tells the interpreter that the folder is a python package.

Second thing to look for is that pycharm likes to complain about imported code if PyCharm does not know about that directory. Go into the Project Interpreter Configuration and go to Paths and add the path references that are not in the project or directly under the interpreter.

One other thing to add, is to set the source root of your project code by right clicking the folder that represents your root and clicking the 'Mark Directory as...' > 'Source Root'.

查看更多
Emotional °昔
3楼-- · 2019-04-23 17:24

I encountered the same issue, but it's not caused by the lack of init.py file. The reason is, there are two same name modules in the project, so PyCharm don't know how to import. The weird thing is PyCharm only report this error on the running time.

My Project Files:

source root1
   |-- moduleA
        |-- __init__.py
        |-- A.py

 source root2
   |-- moduleA
        |-- __init__.py
        |-- B.py

Actually, the source root1 is my code, and source root2 is my test code.

so the solution is to change the test module name.

 source root1
    |-- moduleA
         |-- __init__.py
         |-- A.py

 source root2
    |-- testmoduleA
         |-- __init__.py
         |-- B.py
查看更多
登录 后发表回答