Personal tools
You are here: Home Weblog Archive 2006 August 23 Capturing print statements output
Document Actions
  • Send this page to somebody
  • Print this page
  • Add Bookmarklet

Capturing print statements output

by tibi last modified 2006-08-23 04:45
Filed Under:

Sometimes you have code that has a lot of print statements, which are helping you with debugging. But what happens if you try to port that code to an environment without a console? In the best case, you won't see the prints anymore, in the worse case, the code will fail because there's no "valid file descriptor" to which to write.

The solution to this problem is to replace python's stdout file, which will enable the code output to be recorded and maybe logged for debugging purposes.

The following snippet shows how to achieve this:

>>> import StringIO, sys
>>> out = StringIO.StringIO()
>>> sys.stdout = out
>>> print "Test"
>>> log = out.getvalue()
>>> assert (log == "Test\n")
>>>


Weblog
Atom
RDF
RSS 2.0
Powered by Quills
Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 License.
 

Powered by Plone CMS, the Open Source Content Management System

This site conforms to the following standards: