Hello,
I’m trying to grab (and parse) the output of a root command.
#! /usr/bin/env python
import sys
# a simple class with a write method
class WritableObject:
def __init__ (self):
self.content = []
def write (self, string):
self.content.append(string)
myOutput = WritableObject() # a writable object
sys.stdout = myOutput # redirection
# sys.stderr = myOutput
import ROOT
rootfile = ROOT.TFile.Open ('somefile.root')
tree = rootfile.Get('Events')
print "Hi mom.obj ="
tree.Print()
sys.stdout = sys.__stdout__ # remember to reset sys.stdout!
#sys.stderr = sys.__stderr__
print "Done"
print myOutput.content
When I run this, the ‘Hi mom.obj’ gets caught in myOutput, but the ‘Print()’ command goes to the screen and is not redirected.
How can I do this?
Thanks,
Charles
wlav
June 2, 2009, 11:24pm
2
Charles,
in order to also grab the output from C++, you’ll need to dup the file descriptor and redirect it. This is the basic idea:[code]#! /usr/bin/env python
import sys
class Redirector( object ):
def init ( self, stream ):
import os, sys, tempfile
w, n = tempfile.mkstemp()
os.unlink( n )
self._file = os.fdopen( w, ‘rw’ )
self._stream = stream
self._savefn = os.dup( self._stream.fileno() )
os.dup2( self._file.fileno(), self._stream.fileno() )
def restore( self ):
import os
self._stream.flush()
os.dup2( self._savefn, self._stream.fileno() )
self._file.seek( 0 )
content = ''.join( self._file.readlines() )
self._file.close()
del self._file, self._savefn, self._stream
return content
import ROOT
rootfile = ROOT.TFile.Open (‘somefile.root’)
tree = rootfile.Get(‘Events’)
r = Redirector( sys.stdout )
tree.Print()
print r.restore()[/code]
I’m not sure whether it can be done easily without redirecting to a temporary file.
HTH,
Wim