modules both lines of text are printed to sys stdouta file object that represents the "standard output stream"--this is normally the console and differs from sys stderrthe "error output streamonly in that the latter is unbuffered (python automatically creates and opens sys stdinsys stdoutand sys stderr at program start-up the print(function adds newline by defaultalthough we can stop this by giving the end keyword argument set to an empty string in some situations it is useful to be able to capture into string the output that is intended to go to file this can be achieved using the io stringio class which provides an object that can be used just like file objectbut which holds any data written to it in string if the io stringio object is given an initial stringit can also be read as though it were file we can access io stringio if we do import ioand we can use it to capture output destined for file object such as sys stdoutsys stdout io stringio(if this line is put at the beginning of programafter the imports but before any use is made of sys stdoutany text that is sent to sys stdout will actually be sent to the io stringio file-like object which this line has created and which has replaced the standard sys stdout file object nowwhen the print(and sys stdout write(lines shown earlier are executedtheir output will go to the io stringio object instead of the console (at any time we can restore the original sys stdout with the statement sys stdout sys __stdout__ we can obtain all the strings that have been written to the io stringio object by calling the io stringio getvalue(functionin this case by calling sys stdout getvalue()--the return value is string containing all the lines that have been written this string could be printedor saved to log or sent over network connection like any other string we will see another example of io stringio use bit further on command-line programming |if we need program to be able to process text that may have been redirected in the console or that may be in files listed on the command linewe can use the fileinput module' fileinput input(function this function iterates over all the lines redirected from the console (if anyand over all the lines in the files listed on the command lineas one continuous sequence of lines the module can report the current filename and line number at any time using fileinput filename(and fileinput lineno()and can handle some kinds of compressed files two separate modules are provided for handling command-line optionsoptparse and getopt the getopt module is popular because it is simple to use