self text 'def write(selfstring)self text +string def writelines(selflines)for line in linesself write(lineempty string when created add string of bytes add each line in list class inputsimulated input file def __init__(selfinput='')default argument self text input save string when created def read(selfsize=none)optional argument if size =noneread bytesor all resself text self text'elseresself text self text[:size]self text[size:return res def readline(self)eoln self text find('\ 'find offset of next eoln if eoln =- slice off through eoln resself text self text'elseresself text self text[:eoln+ ]self text[eoln+ :return res def redirect(functionpargskargsinput)savestreams sys stdinsys stdout sys stdin input(inputsys stdout output(tryresult function(*pargs**kargsoutput sys stdout text finallysys stdinsys stdout savestreams return (resultoutputredirect stdin/out run function object return stdout text run function with args restore if exc or not return result if no exc this module defines two classes that masquerade as real filesoutput provides the write method interface ( protocolexpected of output files but saves all output in an in-memory string as it is written input provides the interface expected of input filesbut provides input on demand from an in-memory string passed in at object construction time the redirect function at the bottom of this file combines these two objects to run single function with input and output redirected entirely to python class objects the passed-in function to run need not know or care that its print and input function calls and stdin and stdout method calls are talking to class rather than to real filepipeor user to demonstrateimport and run the interact function at the heart of the test streams script of example - that we've been running from the shell (to use the script execution context