以下是此測試中的文件:main.pyapp/ |- __init__.py |- master.py |- plugin/ |- |- __init__.py |- |- p1.py |- |_ p2.py這個(gè)想法是要有一個(gè)具有插件功能的應(yīng)用程序??梢詫⑿碌?py或.pyc文件放入符合我的API的插件中。我master.py在應(yīng)用程序級別有一個(gè)文件,其中包含任何和所有插件都可能需要訪問的全局變量和函數(shù),以及應(yīng)用程序本身。為了進(jìn)行此測試,“ app”由app / __ init__.py中的測試功能組成。在實(shí)踐中,該應(yīng)用程序可能會(huì)移動(dòng)到單獨(dú)的代碼文件中,但是隨后我將import master在該代碼文件中使用來引入對的引用master。這是文件內(nèi)容:main.py:import appapp.test()app.test2()app / __ init__.py:import sys, osfrom plugin import p1def test(): print "__init__ in app is executing test" p1.test()def test2(): print "__init__ in app is executing test2" scriptDir = os.path.join ( os.path.dirname(os.path.abspath(__file__)), "plugin" ) print "The scriptdir is %s" % scriptDir sys.path.insert(0,scriptDir) m = __import__("p2", globals(), locals(), [], -1) m.test()app / master.py:myVar = 0app / plugin / __ init__.py:<empty file>app / plugin / p1.py:from .. import masterdef test(): print "test in p1 is running" print "from p1: myVar = %d" % master.myVarapp / plugin / p2.py:from .. import masterdef test(): master.myVar = 2 print "test in p2 is running" print "from p2, myVar: %d" % master.myVar由于我顯式導(dǎo)入了p1模塊,因此一切正常。但是,當(dāng)我__import__導(dǎo)入p2時(shí)執(zhí)行將一直執(zhí)行到test()函數(shù),并在test2()嘗試執(zhí)行其__import__語句時(shí)出錯(cuò),這反過來又使p2嘗試進(jìn)行相對導(dǎo)入(當(dāng)通過import語句顯式導(dǎo)入p1時(shí),它才起作用) )顯然,using__import__所做的事情與使用該import語句有所不同。Python文檔指出,使用import可以在__import__內(nèi)部簡單地轉(zhuǎn)換為一條語句,但是要做的事情還不止于此。由于該應(yīng)用程序是基于插件的,因此在主應(yīng)用程序中編碼顯式導(dǎo)入語句當(dāng)然是不可行的。在我在這里想念什么?當(dāng)使用手動(dòng)導(dǎo)入模塊時(shí),如何使Python表現(xiàn)出預(yù)期的效果__import__?似乎我不太了解相對導(dǎo)入的概念,或者我只是缺少有關(guān)導(dǎo)入發(fā)生位置的信息(即在函數(shù)內(nèi)部而不是代碼文件的根目錄)
添加回答
舉報(bào)
0/150
提交
取消