Importing modules from different directories

孤人 提交于 2019-12-11 19:37:40

问题


I have a problem importing a module: It is under this directory ./dao and the code that calls it is here ./core. Schematically represented as:

rnaspace/
 __init__.py
 core/
   __init__.py
   logger.py
 dao/
   __init__.py
   storage_configuration_reader.py

This is the error message:

Traceback (most recent call last):   File "logger.py", line 21, in <module>
    from rnaspace.dao.storage_configuration_reader import storage_configuration_reader ImportError: No module named rnaspace.dao.storage_configuration_reader

This file it is there /rnaspace/dao/storage_configuration_reader.py and in the same folder the __init__.py file as follows:

""" Package dao
    Gathers files that access to the plateform data 
"""

If I understood well this question, it should work. I think that the problem is that one is not the subdirectory of the other (or that the path is not exaclly that one), there is a way to go around it? Or need I to apply the solution to this question?

EDIT The __init__.py file of the rnaspace folder:

import rnaspace.dao.storage_configuration_reader as scr

def update_conf(conf_path, predictors_conf_dir):
    scr.update_conf(conf_path, predictors_conf_dir)

回答1:


from rnaspace.dao.storage_configuration_reader import storage_configuration_reader

That is wrong because there is no "storage_configuration_reader" directory in "dao" directory

This is how it should be:

from rnaspace.dao import storage_configuration_reader

EDIT:

or this way:

import rnaspace.dao.storage_configuration_reader



回答2:


I finally found the solution in another question, it is using the module imp.
I just needed to add the name of the module, and the absolute path where it was:

imp.load_source("storage_configuration_reader","./rnaspace/dao/storage_configuration_reader.py")


来源:https://stackoverflow.com/questions/21855430/importing-modules-from-different-directories

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