结构导入错误:“fab task”与“from fabfile import task;task()”

2024-06-16 11:40:49 发布

您现在位置:Python中文网/ 问答频道 /正文

这也与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:

^{pr2}$

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语句的参数?在


Tags: 函数textfrompyimport文件夹hellohome
1条回答
网友
1楼 · 发布于 2024-06-16 11:40:49

这是织物的已知问题。在Github上Fabric的问题跟踪器中有几个关于它的问题。例如,请参见issue #256。在

解决方法

你可以把

from secret import TEXT

或将当前目录添加到模块搜索路径中。在

^{pr2}$

相关问题 更多 >