簡體   English   中英

如何從使用 importlib 導入的 package 執行模塊

[英]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,

在變量中使用testpackageBtestb

我找到了解決方案:

如何執行動態導入的包模塊函數

文件夾結構:

- testpackageB
   - testb.py
       def testb(): ....

- main.py

測試包B/testb.py

__all__ = ['testb']

def testb():
    print("Hello World from testb in testpackageB")
    

測試包B/初始化.py

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM