python importlib動態導入模塊

  通常而言,當咱們須要某些功能的模塊時(不管是內置模塊或自定義功能的模塊),能夠經過import module 或者 from * import module的方式導入,這屬於靜態導入,很容易理解。html

  而若是當咱們須要在程序的運行過程時才能決定導入某個文件中的模塊時,而且這些文件提供了一樣的接口名字,上面說的方式就不適用了,這時候須要使用python 的動態導入。python

importlib使用

  如在scripts目錄中保存着一些功能模塊,向外提供相似的接口poc()和腳本描述信息description,須要傳入一個參數target,固然腳本執行的功能是不同的,如下只是舉例:編程

starnight:EXP-M starnight$ ls scripts/
__init__.py     __pycache__ test1.py test2.py test3.py starnight:EXP-M starnight$ cat scripts/test1.py #!/usr/bin/env python # -*- coding:utf-8 -*-
 description = 'it is a test1'


def poc(target): print('it is a test1') return True

  而咱們須要動態傳入腳本名,來選用此時要執行的功能:函數

#!/usr/bin/env python # -*- coding:utf-8 -*-

import importlib script_name = input('please input script_name : ')     # 手動輸入腳本名                module = importlib.import_module('scripts.{}'.format(script_name))    # 動態導入相應模塊 func = module.poc('')      # 執行腳本功能 print(module.description)    # 獲取腳本描述信息
please input script_name : test1 it is a test1 it is a test1 ... please input script_name : test3 it is a test3 it is a test3

  當咱們動態給定腳本名字時,就會動態的導入該模塊,執行相應的功能。this

importlib其餘介紹

  python doc: importlibspa

  importlib中的幾個函數:__import__、import_module、find_loader、invalidate_caches、reloadcode

"Note Programmatic importing of modules should use import_module() instead of this function."

  當進行編程時,使用import_module,如上使用該模塊。orm

  find_loader用來查找模塊,reload從新載入模塊,invalidate_caches很少介紹了。htm

相關文章
相關標籤/搜索