ImportError: No module named - Python

后端 未结 6 1609
闹比i
闹比i 2020-11-28 04:52

I have a python application with the following directory structure:

src
 |
 +---- main
 |
 +---- util
 |
 +---- gen_py
         |
         +---- lib
<         


        
相关标签:
6条回答
  • 2020-11-28 05:07

    Make sure if root project directory is coming up in sys.path output. If not, please add path of root project directory to sys.path.

    0 讨论(0)
  • 2020-11-28 05:11

    make sure to include __init__.py, which makes Python know that those directories containpackages

    0 讨论(0)
  • 2020-11-28 05:15

    This is if you are building a package and you are finding error in imports. I learnt it the hard way.The answer isn't to add the package to python path or to do it programatically (what if your module gets installed and your command adds it again?) thats a bad way.

    The right thing to do is: 1) Use virtualenv pyvenv-3.4 or something similar 2) Activate the development mode - $python setup.py develop

    0 讨论(0)
  • 2020-11-28 05:19

    For the Python module import to work, you must have "src" in your path, not "gen_py/lib".

    When processing an import like import gen_py.lib, it looks for a module gen_py, then looks for a submodule lib.

    As the module gen_py won't be in "../gen_py/lib" (it'll be in ".."), the path you added will do nothing to help the import process.

    Depending on where you're running it from, try adding the relative path to the "src" folder. Perhaps it's sys.path.append('..'). You might also have success running the script while inside the src folder directly, via relative paths like python main/MyServer.py

    0 讨论(0)
  • 2020-11-28 05:26

    Your modification of sys.path assumes the current working directory is always in main/. This is not the case. Instead, just add the parent directory to sys.path:

    import sys
    import os.path
    
    sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
    import gen_py.lib
    

    Don't forget to include a file __init__.py in gen_py and lib - otherwise, they won't be recognized as Python modules.

    0 讨论(0)
  • 2020-11-28 05:28
    from ..gen_py.lib import MyService
    

    or

    from main.gen_py.lib import MyService
    

    Make sure you have a (at least empty) __init__.py file on each directory.

    0 讨论(0)
提交回复
热议问题