织物-有什么方法可以捕获运行stdout吗?

2024-05-15 16:50:54 发布

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

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

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

有没有办法把stdoutls发送到output


更具体地说,我正在使用一个名为s3cmd的CLI应用程序,它做了一些类似于ls的事情,但是使用了远程Amazon S3存储桶。

因此,替换ls并没有帮助。



Tags: runin应用程序foroutputclistdoutline
3条回答

如果需要使用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)

我希望有帮助。

使用字符串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)

正是你所要求的。从docs

run will return the result of the remote program’s stdout as a single (likely multiline) string.

run(),以及诸如local()sudo()之类的相关命令,返回一个_AttributeString对象,该对象只是stdout的包装器,具有对诸如failure/success booleans、stderr、command run等附加信息的属性访问。result对象还有一个stdout属性,该属性更加明确。

要排除故障,print type(output), output确保响应符合您的预期。检查output.failedoutput.stderr。可能是命令没有按预期执行,没有“backups”目录等

相关问题 更多 >