2013-04-15 63 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)