Python Fabric将输出保存到变量

Mik*_*e A 3 python fabric

我正在尝试将Fabric中的sudo命令的输出保存到变量中,因此我可以拖尾文件.我的代码看起来像这样:

def tail_pg():
    log = StringIO();
    sudo('ls -t /var/lib/pgsql/9.3/data/pg_log/| head -n 1', stdout=log)

    print type(log), log
    sudo('tail -n 25 -f %s' % log, pty=True)
Run Code Online (Sandbox Code Playgroud)

我添加了print语句作为故障排除的一部分.它返回这些值而不是日志文件名:

<type 'instance'> <StringIO.StringIO instance at 0x10345f638>
Run Code Online (Sandbox Code Playgroud)

我似乎正在关注运行(链接)的Fabric文档,但我必须忽略一些东西.这是我在运行此任务时收到的错误:

[centos] Executing task 'tail_pg'
[centos] sudo: ls -t /var/lib/pgsql/9.3/data/pg_log/| head -n 1

<type 'instance'> <StringIO.StringIO instance at 0x10345f638>
[centos] sudo: tail -n 25 -f <StringIO.StringIO instance at 0x10345f638>
[centos] out: /bin/bash: -c: line 0: syntax error near unexpected token `newline'
[centos] out: /bin/bash: -c: line 0: `tail -n 25 -f <StringIO.StringIO instance at 0x109c313f8>'
[centos] out:


Fatal error: sudo() received nonzero return code 1 while executing!

Requested: tail -n 25 -f <StringIO.StringIO instance at 0x109c313f8>
Executed: sudo -S -p 'sudo password:'  /bin/bash -l -c "tail -n 25 -f <StringIO.StringIO instance at 0x109c313f8>"

Aborting.
Disconnecting from centos... done.
Run Code Online (Sandbox Code Playgroud)

Mik*_*ike 5

你应该让它变得有点复杂.真的,stdout/stderr kwarg可以将stderr发送到stdout,如果你想捕获它的话.你可以做点什么

def tail_pg():
    log = sudo('ls -t /var/lib/pgsql/9.3/data/pg_log/| head -n 1')

    print type(log), log
    sudo('tail -n 25 -f %s' % log, pty=True)
Run Code Online (Sandbox Code Playgroud)

fabric将从run()和sudo()返回stdout,以便将其捕获到变量中.