Python Fabric将输出保存到Variab

2024-06-08 00:37:46 发布

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

我试图将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)

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

<type 'instance'> <StringIO.StringIO instance at 0x10345f638>

我似乎在关注run(link)的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.

Tags: instancebashlogbinvartypesudoout
1条回答
网友
1楼 · 发布于 2024-06-08 00:37:46

你让事情变得更复杂了。实际上,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)

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

相关问题 更多 >

    热门问题