python 动态加载模块失败_Python动态加载模块的实现

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值