1

我有一个模块可以导入一些我想覆盖的库。例子:

模块.py

import md5

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

新文件.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

我想避免/*skip* 导入,而不是执行它然后进行替换。

编辑 2

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

4

2 回答 2

2

好吧,您的示例没有多大意义,因为您似乎将aandb视为 中的类newfile.py,但将其视为模块module.py-您实际上无法做到这一点。我想你正在寻找这样的东西......

模块.py

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

新文件.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
于 2013-04-15T15:50:42.413 回答
0

传递一个空的 dicts asglobalslocalsto __import__。从他们那里删除你想要的任何东西,然后更新你的globalsand locals.

tmpg, tmpl = {}, {}
__import__(module, tmpg, tmpl)
# remove undesired stuff from this dicts
globals.update(tmpg)
locals.update(tmpl)
于 2013-04-15T15:20:38.790 回答