以下是此测试中的文件:main.pyapp/ |- __init__.py |- master.py |- plugin/ |- |- __init__.py |- |- p1.py |- |_ p2.py这个想法是要有一个具有插件功能的应用程序。可以将新的.py或.pyc文件放入符合我的API的插件中。我master.py在应用程序级别有一个文件,其中包含任何和所有插件都可能需要访问的全局变量和函数,以及应用程序本身。为了进行此测试,“ app”由app / __ init__.py中的测试功能组成。在实践中,该应用程序可能会移动到单独的代码文件中,但是随后我将import master在该代码文件中使用来引入对的引用master。这是文件内容: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由于我显式导入了p1模块,因此一切正常。但是,当我__import__导入p2时执行将一直执行到test()函数,并在test2()尝试执行其__import__语句时出错,这反过来又使p2尝试进行相对导入(当通过import语句显式导入p1时,它才起作用) )显然,using__import__所做的事情与使用该import语句有所不同。Python文档指出,使用import可以在__import__内部简单地转换为一条语句,但是要做的事情还不止于此。由于该应用程序是基于插件的,因此在主应用程序中编码显式导入语句当然是不可行的。在我在这里想念什么?当使用手动导入模块时,如何使Python表现出预期的效果__import__?似乎我不太了解相对导入的概念,或者我只是缺少有关导入发生位置的信息(即在函数内部而不是代码文件的根目录)
添加回答
举报
0/150
提交
取消