I have three files in total in python 2.7:
- A module file in some directory (e.g.
module1.py
) - A different module in the same directory, which imports this module (e.g.
worker.py
) - A main script in the top-level directory importing
worker.py
When the file worker.py
looks as the following
import module1 as mod
everything works as expected (i.e. I can use worker.mod.XXX
in my main code). But when I replace the content of worker.py
as follows (which I expected to do the same):
mod = __import__('module1')
I get an error: ImportError: No module named module1
. I need the latter way to handle things to automate importing modules from a list.
What am I missing here?
To be more precise: I am just looking for a way to replace the statement
import module1 as mod
by an expression in which module1
is a string. I have e.g. modulname='module1'
, and want to import the module with the name of the module given in the string modulname
. How to do that?