1
可能重複:
How to load compiled python modules from memory?蟒蛇:從內存中導入模塊
我在記憶一些Python文件,可能是StringIO.I如何導入存儲在存儲器模塊文件。我不想將它保存到磁盤然後加載。
它看起來像:
import StringIO.StrngIO([buf])
可能重複:
How to load compiled python modules from memory?蟒蛇:從內存中導入模塊
我在記憶一些Python文件,可能是StringIO.I如何導入存儲在存儲器模塊文件。我不想將它保存到磁盤然後加載。
它看起來像:
import StringIO.StrngIO([buf])
一個很好的方法是在PEP 302描述使用自定義元進口掛鉤。我們可以寫一個類,動態進口模塊從字符串的字典:
"""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的實施。你需要的就是它。
http://stackoverflow.com/questions/1830727/how-to-load-compiled-python-modules-from-memory – Himanshu