Importing another project as modules in python

你。 提交于 2019-12-24 17:28:30

问题


Suppose I have a project in the following structure

projectfoo/
|- mymodule/
|--|- __init__.py
|--|- library.py
|- preprocessor.py

and in the __init__.py in mymodule looks like this

from . import library #library itself has other functions

def some_function():
    blar blar blar...

and the preprocessor.py would look like follows

import mymodule

def main():
    something()

def something():
    mymodule.some_function() # calls the function defined in __init__.py

if __name__ == '__main__':
    main()

Then I started projectbar, which is using a lot of common code from projectfoo. So instead of copying and pasting code between projects, I wish to import projectfoo into project bar, as follows.

projectbar/
|- projectfoo/
|--|- mymodule/
|--|--|- __init__.py
|--|--|- library.py
|--|- preprocessor.py
|- index.py

So I am trying to import preprocessor in my index.py as follows

from projectfoo import preprocessor

However I am getting an error saying preprocessor.py is now unable to import mymodule.

ImportError: No module named 'mymodule'

Am I doing this correctly? I am using python3.4 running in ubuntu 14.04 in my setup.

EDIT: I also tried adding __init__.py to projectfoo, but I am still getting the same error


回答1:


You are getting this error because you did not added the path of preprocessor as a library package

from sys import path as pylib #im naming it as pylib so that we won't get confused between os.path and sys.path 
import os
pylib += [os.path.abspath(r'/projectfoo')]
from projectfoo import preprocessor

FYI: os.path will return the absolute path. but sys.path will return the path env. variable in system settings.

Hope it helps.




回答2:


Try to add empty __init__.py to projectfoo folder.




回答3:


You have to add an __init__.py file (can be empty) in your projectfoo/ folder to make it a valid module.

Then use relative imports to explicitly specify you're requesting the current module's submodule mymodule like this:

from .projectfoo import preprocessor

The . stands for the current module in which the file containing the import statement is located. Its parent module would be denoted as .., its "grandparent" would be ... etc.



来源:https://stackoverflow.com/questions/36996391/importing-another-project-as-modules-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!