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?
2 Answers 2
__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module
Import a module. Because this function is meant for use by the Python
interpreter and not for general use it is better to use
importlib.import_module() to programmatically import a module.
The globals argument is only used to determine the context;
they are not modified. The locals argument is unused. The fromlist
should be a list of names to emulate from name import ..., or an
empty list to emulate import name.
When importing a module from a package, note that __import__('A.B', ...)
returns package A when fromlist is empty, but its submodule B when
fromlist is not empty. Level is used to determine whether to perform
absolute or relative imports. -1 is the original strategy of attempting
both absolute and relative imports, 0 is absolute, a positive number
is the number of parent directories to search relative to the current module.
9 Comments
importlib, but importlib.import_module('module1') gives the same error.import module1 as mod by an expression in which module1 is used as string. I have e.g. modulname='module1', and now I want to import the module with the name as defined in the string modulname. How to do that?try this:
mod = __import__('module1', globals=globals())
__import__()is directly invoked by theimportstatement.