Importing modules from different directories

2019-08-27 16:11发布

问题:

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")