![](/img/trans.png)
[英]ModuleNotFoundError using “classic” import on module imported from importlib
[英]How to execute a module from a package imported with importlib
我在 package 中有一個名為testpackageB
的模塊
模塊名為testb.py
,內容如下:
__all__ = ['testb']
def testb():
print("Hello World from Test B in testpackageB")
package目錄下的__init__.py
文件包含:
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()
我不明白也找不到的是對這個問題的簡單回答:
我如何在這個主要的 function 中執行 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
所以,我改一下問題:
我如何在這個主要的 function 中執行 testpackageB.testb,
在變量中使用testpackageB
和testb
?
我找到了解決方案:
- testpackageB
- testb.py
def testb(): ....
- main.py
__all__ = ['testb']
def testb():
print("Hello World from testb in testpackageB")
from testpackageB import testb
import importlib
if __name__ == "__main__":
package = "testpackageB"
module = "testb"
function = "testb"
tt = importlib.import_module(f".{module}", package)
func = getattr(tt, function)
if func:
func()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.