Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

importing a module when the module name is in a variable [duplicate]

Possible Duplicate:
Dynamic module import in Python

I am writing a small script that gets the name of a file from a directory and passes this to another module which then imports the file.

so the flow is like 1) get module name ( store it in a variable) 2) pass this variable name to a module 3) import the module whose name is stored in the variable name

my code is like

data_files = [x[2] for x in os.walk(os.path.dirname(sys.argv[0]))] hello = data_files[0] modulename = hello[0].split(".")[0]  import modulename 

the problem is when it reaches the import statement, it reads modulename as a real module name and not the value stored in this variable. I am unsure about how this works in python, any help on solving this problem would be great

like image 686
user1801279 Avatar asked Nov 28 '12 04:11

user1801279


People also ask

Can we import a module twice?

If a module is imported multiple times, but with the same specifier (i.e. path), the JavaScript specification guarantees that you'll receive the same module instance.

What is __ import __ in Python?

__import__() Parameters name - the name of the module you want to import. globals and locals - determines how to interpret name. fromlist - objects or submodules that should be imported by name. level - specifies whether to use absolute or relative imports.

Can we import same package twice in Python?

What happens if a module is imported twice? The module is only loaded the first time the import statement is executed and there is no performance loss by importing it again. You can examine sys. modules to find out which modules have already been loaded.


2 Answers

importlib is probably the way to go. The documentation on it is here. It's generally preferred over __import__ for most uses.

In your case, you would use:

import importlib module = importlib.import_module(module_name, package=None) 
like image 28
munk Avatar answered Oct 12 '22 05:10

munk


You want the built in __import__ function

new_module = __import__(modulename) 
like image 138
mgilson Avatar answered Oct 12 '22 05:10

mgilson