Python 在运行时加载模块在结构下除外
我在一个目录中有两个文件:loader.py和mod1.py。ploader.py动态实例化mod1.py中的类并对其调用方法。这是mod1.pyPython 在运行时加载模块在结构下除外,python,dynamic,fabric,Python,Dynamic,Fabric,我在一个目录中有两个文件:loader.py和mod1.py。ploader.py动态实例化mod1.py中的类并对其调用方法。这是mod1.py class MyClass1: def run(self): print "Class1 running" 这里是加载器: def run(): mod = __import__('mod1') cls = getattr(mod, 'MyClass1') inst = c
class MyClass1:
def run(self):
print "Class1 running"
这里是加载器:
def run():
mod = __import__('mod1')
cls = getattr(mod, 'MyClass1')
inst = cls()
inst.run()
run()
如果我直接运行python:“python loader.py”,我会看到:
这就是你所期望的。如果我在fabric下运行它:“fab-f loader.py run”我明白了
这很有意义,run()由fabric和loader.py调用,当它由fabric加载时
但是,如果我删除了在loader.py中运行的显式调用,因此在fabric下只调用一次,那么
ImportError: No module named mod1
为什么在布料下跑步会有不同?有没有办法让这项工作在fabric下进行?以下是我的见解
这种奇怪的行为在中有解释,引用:
Fabric对fabfile执行正常导入(实际上是_导入)
为了访问其内容,它不进行任何评估或
类似的。为了使其工作,Fabric临时添加找到的
将fabfile的包含文件夹添加到Python加载路径(并将其删除)
紧接着。)
查看修改后的loader.py
:
import os
import sys
print sys.path # current dir is in sys.path
def run():
print sys.path # current dir is NOT in sys.path
# no problem - we'll just add it
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
mod = __import__('mod1')
cls = getattr(mod, 'MyClass1')
inst = cls()
inst.run()
看起来很难看,但它解决了问题
fabric在加载fab文件时如何处理导入。也是相关的
希望有帮助。将init.py文件添加到目录中会有帮助吗?仅仅存在init.py文件并没有任何区别。答案最终会有帮助吗?谢谢
ImportError: No module named mod1
import os
import sys
print sys.path # current dir is in sys.path
def run():
print sys.path # current dir is NOT in sys.path
# no problem - we'll just add it
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
mod = __import__('mod1')
cls = getattr(mod, 'MyClass1')
inst = cls()
inst.run()