Python动态加载模块的实现

    xiaoxiao2021-03-25  114

    Python是通过import来实现模块加载的。有时候我们在事先并不知道到底需要加载哪些模块,只有在程序运行到一定阶段后才能够明确加载模块的信息,这就涉及到动态加载的问题了。

    创建如下代码组成形式:

    运行test.py,需要在代码中动态加载exploit包中的exp1.py和exp2.py。

    exp1.py:

    class Poc(object): def test(self): print 'exp1',__name__

    exp2.py:

    class Poc(object): def test(self): print 'exp2',__name__

    test.py中实现动态加载:

    #condig:utf-8 import os import sys path=os.path.abspath('.') exploit_path=os.path.join(path,'exploit') sys.path.append(exploit_path) modules=[x for x in os.listdir(exploit_path) if os.path.isfile(os.path.join(exploit_path,x)) and os.path.splitext(x)[1]=='.py'] for m in modules: if m!='__init__.py': module_name=os.path.join(exploit_path,os.path.splitext(m)[0]) class_name='Poc' method_name='test' module=__import__(os.path.splitext(m)[0]) c=getattr(module,class_name) e=c() e.test()
    转载请注明原文地址: https://ju.6miu.com/read-17887.html

    最新回复(0)