gpt4 book ai didi

python - 织物导入错误 : "fab task" vs. "from fabfile import task; task()"

转载 作者:太空宇宙 更新时间:2023-11-04 05:52:02 25 4
gpt4 key购买 nike

这也与 Python 的导入机制有关,特别是与在函数内使用 import 有关。使用 Python 2.7.9 和 Fabric 1.10.0,创建以下三个文件:

fabfile.py:

from another import another_hello
def hello():
print 'hello, world'
another_hello()

另一个.py:

def another_hello():
from secret import TEXT

print 'Hello, world!'
print 'text: ' + TEXT

secret/__init__.py:(同时创建文件夹secret/)

TEXT = 'secret'

现在试试 fab hello。它提示:

  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

同时,你可以很方便的启动一个解释器,输入从 fab 导入你好;你好()。完美运行:

In [2]: from fabfile import hello; hello() 
hello, world
Hello, world!
text: secret

为什么会有这种差异?

现在,我找到了使这项工作可行的技巧。只需将 import secret 添加到 fabfile.py 的开头即可。我认为发生的事情是 fab 工具在打开 fabfile.py 以查找特定任务时仅适用于适当的 PYTHONPATH,但是一旦它已经导入了任务并开始实际运行它,然后发生了一些变化,因此它无法再访问原始文件夹。

我的技巧可行吗?但它不会破坏封装,最后说,因为 fabfile.py 应该知道它调用的任何函数或方法的所有间接依赖?也许这是反对函数内的 import 语句的论据?

最佳答案

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

解决方法

你可以放

from secret import TEXT

another.py的第一行或者将当前目录添加到模块搜索路径。

def another_hello():

import sys
sys.path.insert(0, '')

from secret import TEXT

print 'Hello, world!'
print 'text: ' + TEXT

关于python - 织物导入错误 : "fab task" vs. "from fabfile import task; task()",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29813233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com