llrs
llrs

Reputation: 3397

Importing a module with imp

I have a script that does the following:

import imp
imp.load_source("storage_configuration_reader","/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao/storage_configuration_reader.py")

Later on, I call a class of the this module with the same name:

config = storage_configuration_reader()

If I import it like the above I get the following NameError NameError: global name 'storage_configuration_reader' is not defined but if I use the following code:

import imp
imp.load_source("storage_configuration_reader","/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao/storage_configuration_reader.py")
import storage_configuration_reader
config = storage_configuration_reader()

Then I get this error TypeError: 'module' object is not callable

Changing the name of the imp.load_source doesn't help to import the object:

import imp
imp.load_source("storage_configuration","/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao/storage_configuration_reader.py") 
<module 'storage_configuration' from '/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao/storage_configuration_reader.pyc'>
 import storage_configuration
 config = storage_configuration_reader()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'storage_configuration_reader' is not defined

Which is the best way (AKA working way) to import an object like this?

Info: The storage_configuration_reader definition:

class storage_configuration_reader(object):
    """ 
    Class configuration_reader: this object read the config file and return the 
    different configuration values
    """
    ...

Upvotes: 1

Views: 4660

Answers (1)

zhangxaochen
zhangxaochen

Reputation: 33997

imp.load_source loads the module using the given path and name it using the new name, it's not like from your_module_at_path import your_class_by_name, it's just like import your_module_at_path as new_name (not exactly the same).

Besides, you need to assign the name to a variable to use it:

wtf=imp.load_source("new_module_name", your_path)
#wtf is the name you could use directly:
config = wtf.storage_configuration_reader()

the name new_module_name is stored as a key in dictionary sys.modules, you can use it like this:

sys.modules['new_module_name'].storage_configuration_reader()

A simpler way to import a module from some other directory is adding the module's path to sys.path:

import sys
sys.path.append("/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao")
import storage_configuration_reader
config = storage_configuration_reader.storage_configuration_reader()

Upvotes: 3

Related Questions