How to correct use import when importing neighbor

2019-06-28 08:36发布

问题:

my projects directory looks that:

-project
    -moduleA
        -a.py
        -__init__.py
    -moduleB
        -b.py
        -__init__.py

in file a.py I want to import function from b.py, pycharm suggest me to do it in this way

#file a.py
from moduleB.b import function

then I execute a.py from pycharm evrythinks work, but when I try to do it from command line, python do not see this module:

Traceback (most recent call last):
  File "moduleA\a.py", line 1, in <module>
    from moduleB.b import  function
 ImportError: No module named moduleB.b

回答1:

It is because import in a looks for /moduleB but moduleA doesnt have moduleB package in it. My suggestion is put another py file in project import and call function from there

-project
    -moduleA
       -a.py
       -__init__.py
    -moduleB
       -b.py
       -__init__.py
    main.py


标签: python import