O'Reilly logo

Python Programming On Win32 by Mark Hammond, Andy Robinson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required