0

Lets say this is my project structure :

codes

 - pre.py

training

 - model.py

Both folder have empty __init__.py inside them, and they are at the root folder of my project.

Suppose I want to call pre.py from the model.py :

import sys
sys.path.insert(0, "../codes")
from pre import *

However the code above give me ModuleNotFoundError.

How can I fix this error?

10
  • 2
    You don't need to specify .py extension, try from pre import * Commented Oct 2, 2017 at 12:43
  • Actually you must not specify .py in import statement Commented Oct 2, 2017 at 12:44
  • well, using a setup.py at the outermost level and installing this as a package is IMO a better solution as this will help you to get rid of all the sys.path things and use the import directly as you are doing for all other packages. Commented Oct 2, 2017 at 12:46
  • Ups sorry the .py part is just a typo, my realcode dont use it (but still get the error regardless) Commented Oct 2, 2017 at 12:48
  • This issue with your code is that sys.path is relative to the current interpreter directory, not to the file being executed. So your code may only work if run from training directory. Commented Oct 2, 2017 at 12:50

2 Answers 2

3

You can create a setup.py file at the outermost level. So your directory tree may look like this

|_project_name
  |_codes
    |_pre.py
    |___init__.py
  |_training
    |_models.py
    |___init__.py
  |___init__.py
|_setup.py

Then in the setup.py do something like this

from distutils.core import setup
from setuptools import find_packages

requires = [
    'six>=1.10.0',
]

if __name__ == "__main__":
    setup(
        name="project-name",
        version="0.0.1",
        packages=find_packages(),
        author='Your Name',
        author_email='[email protected]',
        install_requires=requires,
        description='The API to fetch data from different sources',
        include_package_data=True,
    )

And finally from the outermost directory use python setup.py install it will install your package and then you will be able to easily do from project_name.pre import * in models

Also consider using a virtualenv for this kind of things.

Hope this helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Happy it helped :)
1

try using full path of your code folder

import sys
sys.path.insert(0, "fullpath")
from pre import *

1 Comment

I prefer relative path because I used 2 different OS But yes its working using the full path. Thanks for the help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.