Dark Knight
Dark Knight

Reputation: 307

Python ImportLib 'No Module Named'

I'm trying to use a variable as a module to import from in Python.

Using ImportLib I have been successfully able to find the test...

sys.path.insert(0, sys.path[0] + '\\tests')
tool_name = selected_tool.split(".")[0]
selected_module = importlib.import_module("script1")
print(selected_module)

... and by printing the select_module I can see that it succesfully finds the script:

<module 'script1' from 'C:\\Users\\.....">

However, when I try to use this variable in the code to import a module from it:

from selected_module import run
run(1337)

The program quits with the following error:

ImportError: No module named 'selected_module'

I have tried to add a init.py file to the main directory and the /test directory where the scripts are, but to no avail. I'm sure it's just something stupidly small I'm missing - does anyone know?

Upvotes: 0

Views: 4809

Answers (1)

MisterMiyagi
MisterMiyagi

Reputation: 50126

Import statements are not sensitive to variables! Their content are treated as literals

An example:

urllib = "foo"
from urllib import parse   # loads "urllib.parse", not "foo.parse"
print(parse)

Note that from my_module import my_func will simply bind my_module.my_func to the local name my_func. If you have already imported the module via importlib.import_module, you can just do this yourself:

# ... your code here
run = selected_module.run  # bind module function to local name

Upvotes: 1

Related Questions