Contents
任意后缀名文本as模块
需求
MuSheng <[email protected]> reply-to [email protected] to [email protected] date Fri, Mar 13, 2009 at 11:05 subject [CPyUG:81220] 可不可以從多行字符作為一個模塊快導入
由於文件命名問題不能直接用import載入模塊,用eval好像不能執行多行字符串,用imp模塊的load_**函數得不到想要的結果。
- 如將下面代碼命名為form1.py.gui,現在需要將它作為模塊載入
#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 <[email protected]> reply-to [email protected] to [email protected] date Fri, Mar 13, 2009 at 12:36
其他扩展名也是同样可以导入模块的, 用 imputil 模块注册 .gui 后缀就好
例如
就可以了
- MuSheng
- 感謝兄弟,看了下python2.6的文檔,發現在python3中這個模塊會被移除,鬱悶哦。為了以後好移植,再看下有沒好辦法
沈崴自制加载器
沈崴 <[email protected]> reply-to [email protected] to python-cn`CPyUG`华蟒用户组 <[email protected]> date Fri, Mar 13, 2009 at 15:37
1 import sys, os.path
2
3 Module = type(sys)
4 modules = {}
5
6 def load(fullpath, env={}, module=Module):
7 try:
8 code = open(fullpath).read()
9 except IOError:
10 raise ImportError, 'No module named %s' %fullpath
11
12 filename = os.path.basename(fullpath)
13
14 try:
15 return modules[filename]
16 except KeyError:
17 pass
18
19 m = module(filename)
20 m.__module_class__ = module
21 m.__file__ = fullpath
22
23 m.__dict__.update(env)
24
25 exec compile(code, filename, 'exec') in m.__dict__
26 modules[filename] = m
27
28 return m
29
30 def unload(m):
31 filename = os.path.basename(m.__file__)
32 del modules[filename]
33
34 return None
35
36 def reload(m):
37 fullpath = m.__file__
38
39 try:
40 code = open(fullpath).read()
41 except IOError:
42 raise ImportError, 'No module named %s' %fullpath
43
44 env = m.__dict__
45 module_class = m.__module_class__
46
47 filename = os.path.basename(fullpath)
48 m = module_class(filename)
49
50 m.__file__ = fullpath
51 m.__dict__.update(env)
52 m.__module_class__ = module_class
53
54 exec compile(code, filename, 'exec') in m.__dict__
55 modules[filename] = m
56
57 return m
text2module()
def text2module(text, env={}): code = compile(text) module = Module('<string>') module.__dict__.update(env) exec code in module.__dict__ return module
反馈
创建 by -- ZoomQuiet [2009-03-14 01:19:56]