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__':


#music21, #python

Run Ipython magic functions from your profile startup python script

This is the  setup I did for a Music21 project named “chordMe”.

On WIN XP the .ipython configuration dir is in C:Documents and SettingsAdministrator.ipython

Create a profile for your project.

Open a command line shell and type the following to create a new profile

> ipython profile create chordMe
[ProfileCreate] Generating default config file: u'C:Documents and'

Now add the following python file to:
C:Documents and SettingsAdministrator.ipythonprofile_chordMestartup  file content:
# usage:
#     $ ipython --profile=chordMe

import os
from IPython.core.interactiveshell import InteractiveShell 

# from
# run_line_magic(magic_name, line)
# magic_name : str  "Name of the desired magic function, without ‘%’ prefix."
# line : str "The rest of the input line as a single string."

get_ipython().run_line_magic(u"logstart", u"-o append")
from music21 import *

Running Ipython with the startup commands. 
To the command line say:
> ipython --profile=chordMe

#ipython, #music21, #python