天天看點

在python中實作動态導入子產品importlib.import_module

有時候,我們很需要在程式運作的過程中,根據變量或者配置動态的決定導入哪個子產品。

假設我們需要導入的子產品module_12定義在subPack1檔案夾下面,内容如下。

def funcA12(): 

    print('funcA12 in module_12') 

    return 

import os 

print  os.path.join(os.path.abspath(os.path.dirname(__file__)),('templates')) 

print os.path.join(os.path.relpath(os.path.dirname(__file__)),'..templates') 

在這個子產品的上層需要動态導入這個子產品,可以使用下面的代碼。

使用importlib子產品的import_module方法就可以實作動态的導入。

import importlib 

mo =importlib.import_module('subPack1.module_12') 

mo.funcA12() 

本文轉自 virusswb 51CTO部落格,原文連結http://blog.51cto.com/virusswb/794685,如需轉載請自行聯系原作者