覆盖Python库依赖项

时间:2013-04-15 15:11:53

标签: 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

代码已修复(这只是一个例子)。

2 个答案:

答案 0 :(得分:2)

嗯,您的示例没有多大意义,因为您似乎将ab视为newfile.py中的类,但作为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

答案 1 :(得分:0)

将空的dicts传递为globals,将locals传递给__import__。从中删除您想要的任何内容,然后更新您的globalslocals

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