这也与Python的导入机制有关,特别是在函数中使用import
。
使用Python 2.7.9和Fabric 1.10.0,创建以下三个文件:
fabfile.py:
from another import another_hello
def hello():
print 'hello, world'
another_hello()
another.py:
secret/__init__.py:
(同时创建一个文件夹secret/
)
TEXT = 'secret'
{cd6>现在就试试。它抱怨说:
File "/home/sergey/projects/Bask/service/t/fabfile.py", line 4, in hello
another_hello()
File "/home/sergey/projects/Bask/service/t/another.py", line 2, in another_hello
from secret import TEXT
ImportError: No module named secret
同时,你可以很容易地启动一个解释器和打字
from fab import hello; hello()
。完美工作:
In [2]: from fabfile import hello; hello()
hello, world
Hello, world!
text: secret
为什么会有这种区别?在
现在,我找到了一个能让它工作的黑客。只需在fabfile.py
的开头添加一个import secret
。我认为fab
工具只有在打开fabfile.py
来查找某个特定任务时,fab
工具才可以正常工作,但是一旦它导入了任务并开始实际运行它,就会发生一些变化,因此它不再能够访问原始文件夹。在
我的黑客是该走的路吗?但是,最后一点是这样的,因为fabfile.py
应该知道它调用的任何函数或方法的所有间接依赖关系,所以它不破坏封装吗?也许这是一个反对函数内部import
语句的参数?在
这是织物的已知问题。在Github上Fabric的问题跟踪器中有几个关于它的问题。例如,请参见issue #256。在
解决方法
你可以把
或将当前目录添加到模块搜索路径中。在
^{pr2}$相关问题 更多 >
编程相关推荐