Output Buffering Module for Python

Download

To download this module, [ click here ].
It contains the module and HTML documentation.

What is it?

This module implements a simple and effective way of buffering output. It has characteristics that are similar to the way that PHP does it. It differs in numerous ways, however. Most notably, the buffer behaves like a file object (based off of StringIO), which makes it incredibly flexible.

I built this module because Python didn't already have a simple solution to output buffering. The reason I needed it was for a plugin management system that I was building that allowed plugins to use the print statement normally (which transparently buffered the data).

Example

import ob
 
buf = ob.OutputBuffer()
buf.start()  # As of this point, any print statements will be buffered.
 
print "Hello, world!"  # Nothing is printed. "Hello, world!" is saved to the buffer.
 
buf.end()  # Stop buffering output
data = buf.getvalue()  # Gets the data in the buffer

Here, we see a relatively straight-forward example. One neat thing about this module is that if we call buf.start() later on, output buffering starts back up immediately from where it stopped. Any data in the buffer when buf.start() is called will remain there. If you wish to work with a clear buffer, use the clear() method.

Example using a callback

import ob
 
def my_callback(buffer_data):
    return buffer_data.replace("apples", "oranges")
 
buf = ob.OutputBuffer(my_callback)
buf.start() # As of this point, if 'buf' isn't stop()'d before the
               # script ends, then the buffer data will be sent through
               # the callback function and then sent to the writer
               # that is being buffered.
 
print "It's like comparing apples to oranges."
# Output: "It's like comparing oranges to oranges."

In this case, we see an example where buf.stop() never gets called. When that occurs, the output is buffered until the end of the script. The buffered data is then sent through the callback function (if one exists) and finally sent to the writer that has been overridden (typically stdout).

Questions?

Feel free to contact me if you have any unanswered questions! I really hope that this module helps you out.

Trackback