gpt4 book ai didi

python Fabric : filter out server output when capturing output of run()

转载 作者:太空宇宙 更新时间:2023-11-03 11:52:27 29 4
gpt4 key购买 nike

考虑一个 Linux 服务器,它在您的用户的 .bash_profile 中有以下行:

echo "Hello world"

因此,每次您通过 ssh 进入它时,您都会看到 Hello world

现在,考虑以下 脚本:

#!/usr/bin/env python
from fabric.api import *

env.hosts = [...]

@task
def test():
with cd('/'):
print run('ls').split()

你会期望它输出如下内容: ['tmp', 'etc', 'var', ...]

但实际输出将是: ['Hello', 'world', 'tmp', 'etc', 'var', ...]

这是 中的错误吗? ?有什么办法可以抑制服务器输出吗?

time.sleep() 没有帮助

最佳答案

Fabric 执行远程 Bash shell in login mode .这会导致配置文件被执行。您可以通过打开 Debug模式亲眼看到这一点。在我的机器上以 Debug模式执行您的脚本会产生以下结果(除其他外)

[x.x.x.x] Executing task 'test'
[x.x.x.x] run: /bin/bash -l -c "cd / && ls"

注意传递给远程的 -l 调用为了克服这个问题,您可以覆盖 env.shell 以删除 -l 标志,如链接的常见问题解答中所述。

所以改变

with cd('/'):

在你的代码中

with cd('/'), settings(shell='/bin/bash -c'): 

关于 python Fabric : filter out server output when capturing output of run(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22585511/

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