##language:zh #pragma section-numbers off ##含有章节索引导航的 ZPyUG 文章通用模板 <> ## 默许导航,请保留 <> = 任意后缀名文本as模块 = ##startInc == 需求 == {{{ MuSheng reply-to python-cn@googlegroups.com to python-cn@googlegroups.com date Fri, Mar 13, 2009 at 11:05 subject [CPyUG:81220] 可不可以從多行字符作為一個模塊快導入 }}} 由於文件命名問題不能直接用import載入模塊,用eval好像不能執行多行字符串,用imp模塊的load_**函數得不到想要的結果。 * 如將下面代碼命名為form1.py.gui,現在需要將它作為模塊載入 {{{ #!/usr/bin/env python #coding=utf-8 import wx from autoid import AutoId wxId=AutoId() pn1={ 'name':'pn1', 'id':wxId.pn1, 'left':-1, 'top':-1, 'width':-1, 'height':-1, 'style':wx.TAB_TRAVERSAL } form1={ 'title':u'客戶商品資料', 'children':(pn1) } }}} 問下路過的大牛有沒什麼函數可以實現呢? === imputil === {{{ Jiahua Huang reply-to python-cn@googlegroups.com to python-cn@googlegroups.com date Fri, Mar 13, 2009 at 12:36 }}} 其他扩展名也是同样可以导入模块的, 用 imputil 模块注册 .gui 后缀就好 例如 {{{#!python import imputil def handle_gui(fullpath, fileinfo, name): data = file(fullpath).read() return 0, compile(data,fullpath,'exec'),{} im = imputil.ImportManager() im.add_suffix('.gui', handle_gui) im.install() }}} 就可以了 MuSheng:: * 感謝兄弟,看了下python2.6的文檔,發現在python3中這個模塊會被移除,鬱悶哦。為了以後好移植,再看下有沒好辦法 === 沈崴自制加载器 === {{{ 沈崴 reply-to python-cn@googlegroups.com to python-cn`CPyUG`华蟒用户组 date Fri, Mar 13, 2009 at 15:37 }}} {{{#!python import sys, os.path Module = type(sys) modules = {} def load(fullpath, env={}, module=Module): try: code = open(fullpath).read() except IOError: raise ImportError, 'No module named %s' %fullpath filename = os.path.basename(fullpath) try: return modules[filename] except KeyError: pass m = module(filename) m.__module_class__ = module m.__file__ = fullpath m.__dict__.update(env) exec compile(code, filename, 'exec') in m.__dict__ modules[filename] = m return m def unload(m): filename = os.path.basename(m.__file__) del modules[filename] return None def reload(m): fullpath = m.__file__ try: code = open(fullpath).read() except IOError: raise ImportError, 'No module named %s' %fullpath env = m.__dict__ module_class = m.__module_class__ filename = os.path.basename(fullpath) m = module_class(filename) m.__file__ = fullpath m.__dict__.update(env) m.__module_class__ = module_class exec compile(code, filename, 'exec') in m.__dict__ modules[filename] = m return m }}} ==== text2module() ==== {{{ def text2module(text, env={}): code = compile(text) module = Module('') module.__dict__.update(env) exec code in module.__dict__ return module }}} ##endInc ---- '''反馈''' 创建 by -- ZoomQuiet [<>]