Grabbing Python’s Output
You now have
the hooks to execute arbitrary strings of Python code, but you
can’t necessarily see the output. You need to implement one
more feature first, to capture Python’s standard output, so
that print statements in your users’ code
show up properly. You might think this would involve low-level
Windows process control, but actually, Python knows how to redirect
its own output. If you enter the following statements in a Python
source file or the Python DOS prompt, any subsequent output (for
example, print statements) are redirected to a
file:
>>> import sys
>>> mylogfile = open('c:\\temp\\mylog.txt', 'w')
>>> sys.stdout = mylogfile
>>>Output can be redirected to any Python object that offers a
write()
method. The easiest way to grab the
output is to add just such a write() method to our
COMBookSet class, which stores the standard output
internally; provide another method to grab this data from VB on
demand; and start trapping the output when our instance of
COMBookSet starts. Here are the needed extra
methods:
def beginTrappingOutput(self): self.outputBuffer = [] self.old_output = sys.stdout sys.stdout = self def write(self, expr): """ this is an internal utility used to trap the output. add it to a list of strings - this is more efficient than adding to a possibly very long string.""" self.outputBuffer.append(str(expr)) def getStandardOutput(self): "Hand over output so far, and empty the buffer" text = string.join(self.outputBuffer, '') self.outputBuffer ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access