python存文件的模块_python:从内存导入模块

一个很好的方法是使用

PEP 302中描述的自定义Meta导入钩子.可以编写一个从字典字典中动态导入模块的类:

"""Use custom meta hook to import modules available as strings.

Cp. PEP 302 http://www.python.org/dev/peps/pep-0302/#specification-part-2-registering-hooks"""

import sys

import imp

modules = {"a" :

"""def hello():

return 'Hello World A!'""",

"b":

"""def hello():

return 'Hello World B!'"""}

class StringImporter(object):

def __init__(self, modules):

self._modules = dict(modules)

def find_module(self, fullname, path):

if fullname in self._modules.keys():

return self

return None

def load_module(self, fullname):

if not fullname in self._modules.keys():

raise ImportError(fullname)

new_module = imp.new_module(fullname)

exec self._modules[fullname] in new_module.__dict__

return new_module

if __name__ == '__main__':

sys.meta_path.append(StringImporter(modules))

# Let's use our import hook

from a import hello

print hello()

from b import hello

print hello()

顺便说一句:如果你不想那么多,只想导入一个字符串,那么坚持执行方法load_module.所有你需要的都在它里面.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值