I'm trying to save the output of a sudo command in Fabric to a variable, so I can tail a file. My code looks like this:
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)
I added the print statement as part of troubleshooting. It returns these values instead of the logfile name:
<type 'instance'> <StringIO.StringIO instance at 0x10345f638>
I appear to be following the Fabric documentation for run (link), but I must be overlooking something. Here's the error I receive when running this task:
[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.
You are making it a bit more complicated then it should be. Really the stdout/stderr kwarg is there to send the stderr to stdout if you want to capture it. You can just do something like
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 will return stdout from run() and sudo() so you can capture it to a variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With