如何在我的Python Fabric`fabfile.py`中的函数中正确设置`env.hosts`? [英] How can I properly set the `env.hosts` in a function in my Python Fabric `fabfile.py`?
问题描述
当我运行这个 fabfile.py
...
When I run this fabfile.py
...
from fabric.api import env, run, local, cd
def setenv(foo):
env.hosts = ['myhost']
def mycmd(foo):
setenv(foo)
print(env.hosts)
run('ls')
,使用此命令 fab mycmd:bar
。我得到此输出...
with this command fab mycmd:bar
. I get this output...
['myhost']
No hosts found. Please specify (single) host string for connection:
什么,什么?!我不明白吗?我已经设置了 env.hosts
,它似乎在 mycmd
函数内部有效,但是对于某些 run
命令不知道我指定的主机
的原因。
What, what?! I don't get it? I've set the env.hosts
and it seems to be valid "inside" the mycmd
function, but for some reason that run
command doesn't know about the hosts
I've specified.
让我困惑。任何帮助将不胜感激!
Color me confused. Any help would be appreciated!
推荐答案
@Chris,您看到此行为的原因是因为主机列表是构造的<在任务函数之前被调用。因此,即使您要在函数内部更改 env.hosts
,也已为时已晚。
@Chris, the reason you're seeing this behavior is because the host list is constructed before the task function is called. So, even though you're changing env.hosts
inside the function, it is too late for it to have any effect.
命令 fab setenv:foo mycmd:bar
会导致您期望的结果:
Whereas the command fab setenv:foo mycmd:bar
, would have resulted in something you would have expected:
$ fab setenv:foo mycmd:bar
[myhost] Executing task 'mycmd'
['myhost']
[myhost] run: ls
这与接受的答案相同,但是由于定义了setenv
,需要一个参数。
This is the same as the accepted answer, but because of the way setenv
is defined, an argument is needed.
另一个示例:
from fabric.api import env, run, local, cd
env.hosts = ['other_host']
def setenv(foo):
env.hosts = ['myhost']
def mycmd(foo):
setenv(foo)
print('env.hosts inside mycmd: %s' % env.hosts)
run('ls')
此输出是:
$ fab mycmd:bar
[other_host] Executing task 'mycmd'
env.hosts inside mycmd: ['myhost']
[other_host] run: ls
Fatal error: Name lookup failed for other_host
Underlying exception:
(8, 'nodename nor servname provided, or not known')
Aborting.
如您所见,主机列表已设置为 ['架构开始执行
。 mycmd
时,other_host',]
As you can see, the host-list is already set to ['other_host', ]
when fabric starts to execute mycmd
.
这篇关于如何在我的Python Fabric`fabfile.py`中的函数中正确设置`env.hosts`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!