Hau5ratz
Hau5ratz

Reputation: 35

Dynamic importing modules results in an ImportError

So I've been trying to make a simple program that will dynamically import modules in a folder with a certain name. I cd with os to the directory and I run module = __import__(module_name) as I'm in a for loop with all of the files names described being iterated into the variable module_name.

My only problem is I get hit with a:

ImportError: No module named "module_name" 

(saying the name of the variable I've given as a string). The file exists, it's in the directory mentioned and import works fine in the same directory. But normal even import doesn't work for modules in the cd directory. The code looks as follows. I'm sorry if this is an obvious question.

import os

class Book():
    def __init__(self):
        self.name = "Book of Imps"
        self.moduleNames = []

    # configure path
    def initialize(self):
        path = os.getcwd() + '/Imp-pit'
        os.chdir(path)
        cwd = os.walk(os.getcwd())
        x, y, z = next(cwd)
        # Build Modules
        for name in z:
            if name[:3] == 'Imp':
                module_name = name[:len(name) - 3]
                module = __import__(module_name)

def start_sim():
    s = Book()
    s.initialize()

if __name__ == '__main__':
    start_sim()

Upvotes: 3

Views: 1761

Answers (2)

ikreb
ikreb

Reputation: 2775

You should use the try-except concept, e.g.:

try:
    import csv            
except ImportError:
    raise ImportError('<error message>')

If I did understand you correct then

try:
    module = __import__(module_name)
except ImportError:
    raise ImportError('<error message>')

Upvotes: 0

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160437

I don't think the interpreter dynamically alters sys.path if you simply change the current directory with os.chdir. You'll manually have to insert the path variable into the sys.path list for this to work, i.e:

sys.path.insert(0, path)  

Python generally searches sys.path when looking for modules, so it will find it if you specify it there.

An additional note; don't use __import__, rather use importlib.import_module. The interface is exactly the same but the second is generally advised in the documentation.

Upvotes: 3

Related Questions