buff getvalue(' spam \nrestore original stream note that there is also an io bytesio class with similar behaviorbut which maps file operations to an in-memory bytes bufferinstead of str stringfrom io import bytesio stream bytesio(stream write( 'spam'stream getvalue( 'spamstream bytesio( 'dpam'stream read( 'dpamdue to the sharp distinction that python draws between text and binary datathis alternative may be better suited for scripts that deal with binary data we'll learn more about the text-versus-binary issue in the next when we explore files capturing the stderr stream we've been focusing on stdin and stdout redirectionbut stderr can be similarly reset to filespipesand objects although some shells support thisit' also straightforward within python script for instanceassigning sys stderr to another instance of class such as output or stringio object in the preceding section' example allows your script to intercept text written to standard errortoo python itself uses standard error for error message text (and the idle gui interface intercepts it and colors it red by defaulthoweverno higher-level tools for standard error do what print and input do for the output and input streams if you wish to print to the error streamyou'll want to call sys stderr write(explicitly or read the next section for print call trick that makes this easier redirecting standard errors from shell command line is bit more complex and less portable on most unix-like systemswe can usually capture stderr output by using shell-redirection syntax of the form command output >& this may not work on some platformsthoughand can even vary per unix shellsee your shell' manpages for more details redirection syntax in print calls because resetting the stream attributes to new objects was so popularthe python print built-in is also extended to include an explicit file to which output is to be sent statement of this formprint(stufffile=afileafile is an objectnot string name standard streams