繁体   English   中英

Fabric - 有没有办法捕获运行stdout?

[英]Fabric - Is there any way to capture run stdout?

我正在尝试执行以下操作:

output = run("ls -l backups")
for line in output.split("/n"):
    do_stuff(line)

具有的任何stdoutls发送到output


更具体地说,我正在使用名为s3cmd的CLI应用程序,该应用程序执行与ls类似的操作,但使用远程Amazon S3存储桶。

因此,遗憾的是,替换ls无济于事。


你要求的正是应该发生的事情。 来自文档

run将远程程序的stdout的结果作为单个(可能是多行)字符串返回。

run()和相关命令(如local()sudo()返回一个_AttributeString对象,该对象只是stdout的包装器,具有对失败/成功布尔值,stderr,命令运行等其他信息的属性访问权限。结果对象还有一个stdout属性,它更加明确。

要进行故障排除,请print type(output), output以确保响应符合您的预期。 检查output.failedoutput.stderr 它可能是命令没有做你期望的,没有“备份”目录等。

使用String IO尝试如下

from fabric.api import *
from StringIO import StringIO

fh = StringIO()
run("ls -l backups", stdout=fh)

fh.seek(0)
for line in fh.readlines():
    do_stuff(line)

如果你需要使用run(),你可以这样做:

with settings(
    hide('warnings', 'running', 'stdout', 'stderr'),
    warn_only=True
):
    command = 'ls -l backups'
    output = run(command)
    for line in output.splitlines():
        do_stuff(line)

对于local(),有一个更简单的解决方案:

command = 'ls -l backups'
output = local(command, capture=True)
for line in output.splitlines():
    do_stuff(line)

我希望它有所帮助。

如果您使用local() api,也可以通过设置capture=True

@task
def login_ecr_docker():
    ecr_login = local("aws ecr get-login --region us-west-2", capture=True)
    docker_login = ecr_login.stdout
    status = local(docker_login, capture=True)
    print (status.stdout)

尝试使用“ \\r\\n ”拆分:

output = run("ls -l backups")
output_stdout = output.stdout.split("\r\n")

只需简单地返回:

def output():
    return run("ls -l backups")
a = execute(output, host=hostname)
print a

a将是结果字典。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM