如何从用Ementlib导入的软件包执行模块
我在一个称为testpackageb
模块的软件包中有一个模块,
testb.py
带有内容:
__all__ = ['testb']
def testb():
print("Hello World from Test B in testpackageB")
__ init __ init __. py
file the Package Directory包含
from testpackageB import testb
:动态导入该模块的代码如下:
import importlib
if __name__ == "__main__":
tt = importlib.import_module(".testb", "testpackageB")
print(type(tt)) # Shows: <class 'module'>
# All of the following do not work:
# tt["testb"]()
# tt()
# tt.testb()
我不理解和找不到的是一个简单的答案:
我如何在此主要功能中执行testpackageb.testb?
评论我了解到tt.testb()
正在工作。
但这不是您想要的。因为“ testb”是动态的,因此您在变量中具有该名称。
请参阅此代码:(略微更改)
module = "testb"
package = "testpackageB"
tt = importlib.import_module(f".{module}", package)
tt["module"](). # Gives error: TypeError: 'module' object is not subscriptable
,因此,我重新介绍了一个问题:
如何在此主要功能中执行testpackageb.testb,
使用testpackageb
和testb
在变量中?
I have a module in a package called testpackageB
module is called testb.py
with contents:
__all__ = ['testb']
def testb():
print("Hello World from Test B in testpackageB")
The __init__.py
file the package directory contains:
from testpackageB import testb
The code to import this module dynamically is as follows:
import importlib
if __name__ == "__main__":
tt = importlib.import_module(".testb", "testpackageB")
print(type(tt)) # Shows: <class 'module'>
# All of the following do not work:
# tt["testb"]()
# tt()
# tt.testb()
What I don't understand and can't find is a simple answer on the question:
How do I execute testpackageB.testb in this main function?
After getting comments I learned that tt.testb()
is working.
But that is not the one you want. Because 'testb' is dynamic, so you have that name in a variable.
See this code: (slightly changed)
module = "testb"
package = "testpackageB"
tt = importlib.import_module(f".{module}", package)
tt["module"](). # Gives error: TypeError: 'module' object is not subscriptable
So, I rephrase the question:
How do I execute testpackageB.testb in this main function,
with testpackageB
and testb
in variables?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我找到了解决方案:
如何执行动态导入的软件包 - 模块功能
文件夹结构:
testpackageb/testb.py
testpackageb/ init .py
main.py.py
I have found the solution:
How to execute a dynamically imported package-module-function
Folder structure:
testpackageB/testb.py
testpackageB/init.py
main.py