2013-04-15 65 views
0

我有一个模块导入了一些我想覆盖的库。例如:覆盖Python库依赖关系

module.py

import md5 

def test(): 
    print(md5.new("LOL").hexdigest()) 

newfile.py

class fake: 
    def __init__(self, text): 
     self.text = text 
    def hexdigest(self): 
     return self.text 
import sys 
module = sys.argv[1] # It contains "module.py" 
# I need some magic code to use my class and not the new libraries! 
__import__(module) 

编辑1

我想避免/* *跳过进口,而不是执行它然后做一个替代。固定

编辑2

代码(这仅仅是一个例子)。

+0

不,这不是一个重复:我要避免进口,不做替代。 –

+0

另一个downvote?我会尝试更好地解释它:我不想尝试导入库,我想让“导入”无害! :D –

+0

明白了..删除了评论。我不是downvoter :) – karthikr

回答

2

好了,你的例子并没有太大的意义,因为你似乎在newfile.py进行治疗ab为类,但在module.py模块 - 你不能真正做到这一点。我认为你在寻找这样的事情......

module.py

from some_other_module import a, b 
ainst = a("Wow") 
binst = b("Hello") 
ainst.speak() 
binst.speak() 

newfile.py

class a: 
    def __init__(self, text): 
     self.text = text 
    def speak(self): 
     print(self.text+"!") 
class b: 
    def __init__(self, text): 
     self.text = text 
    def speak(self): 
     print(self.text+" world!") 

# Fake up 'some_other_module' 
import sys, imp 
fake_module = imp.new_module('some_other_module') 
fake_module.a = a 
fake_module.b = b 
sys.modules['some_other_module'] = fake_module 

# Now you can just import module.py, and it'll bind to the fake module 
import module 
+0

谢谢,这是我需要的:D –

0

通过一个空的字符作为globalslocals__import__。删除任何你想从他们,然后更新您的globalslocals

tmpg, tmpl = {}, {} 
__import__(module, tmpg, tmpl) 
# remove undesired stuff from this dicts 
globals.update(tmpg) 
locals.update(tmpl)