How to redirect Python’s sys.stdout to StringIO()

Redirect stdout to StringIO()

The following python code will use the capturePrint function to redirect stdio to StringIO() so you can capture info that would normally just be printed. I tested this using the Music21 .show(‘text’) method.


def capturePrint(executableStrThatPrints):

    import sys, StringIO

    # redir sys.stdout
    stdout = sys.stdout
    sys.stdout = reportSIO = StringIO.StringIO()

    reportStr = reportSIO.getvalue()

    # restore sys.stdout so we can print
    sys.stdout = stdout 

    return reportStr

def testCapturePrint():
    from music21 import *
    global sBach
    sBach = corpus.parse('bach/bwv7.7')
    x = capturePrint("""'text')""")
    print x

if __name__ == '__main__':


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s