简体   繁体   English

Python ImportLib“未命名模块”

[英]Python ImportLib 'No Module Named'

I'm trying to use a variable as a module to import from in Python. 我正在尝试使用变量作为模块从Python中导入。

Using ImportLib I have been successfully able to find the test... 使用ImportLib,我已经能够成功找到测试...

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: ...并通过打印select_module,我可以看到它成功找到了脚本:

<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. 我试图将init .py文件添加到脚本所在的主目录和/ test目录中,但无济于事。 I'm sure it's just something stupidly small I'm missing - does anyone know? 我确定这只是我所缺少的小东西-有人知道吗?

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 . 请注意, from my_module import my_func会将my_module.my_func绑定到本地名称my_func If you have already imported the module via importlib.import_module , you can just do this yourself: 如果已经通过importlib.import_module导入了模块,则可以自己执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM