title: Python CGI: Translate from stdout to html (e.g. replace \n with <BR>)
body: <p>I have a great command line program that prints to stdout. I want to let people run this through CGI. In the CGI version, I want to have the same output (with <code>"&lt;BR&gt;"</code> instead of <code>"\n"</code>).</p>
  
  <p>My <code>cgi_main</code> works by calling <code>my real_main</code>; there are a lot of options to process and it was bad design to do that multiple times. But since <code>real_main</code> calls <code>print</code>, I don't know how to change <code>"\n"</code> to <code>"&lt;BR&gt;"</code> post hoc.</p>
  
  <p>I could easily change all instances of <code>print</code> to go to a <code>tempfile</code> and then dump that at the end, but it seems inelegant to change the existing command line version so much.</p>
  
  <p>One option is to have <code>real_main</code> call another function (passing along argv); that new function returns values. Then real_main prints those values. cgi_main would call the same function, but print the values differently.</p>
  
  <p>Another option is to use a class member/static function everywhere I use print now. This class could be told whether to reformat or not. Then switching between command line and CGI output would just require changing the <code>reform</code> argument.</p>
  
  <p>Here is an example of how I thought this class and function could work:
      class cgi_tools:
          def <strong>init</strong>(self, reform = False):
              self.reform = reform
          def myprint(self, *args):
              if not self.reform:
                  print(args)
              for i,x in enumerate(args):
                  if type(x) == str:
                      self.myprint(x.replace('\n', '<BR>')),
                  elif type(x) in atoms: # check if x is an atom (i.e. int, float, etc.):
                      print x,
                  else:
                      self.myprint(x),
                  if i != len(args)-1:
                      print ' ',
              print ''</p>
  
  <p>With this I ran into trouble trying to think of all atoms (i.e. irreducible objects) in Python. I couldn't find a built-in function for this test, and I thought writing it myself was a brittle idea. </p>
  
  <p>I tried to use <code>insepct</code> to print the source code of <code>print</code>, but I couldn't do that!
  print sys.out.print:</p>
  
  <pre><code>import inspect
  print inspect.getsource(print) # this does not work!
  </code></pre>
  
  <p>All of this seems like a classic Python CGI question, but I couldn't find a great solution. I know how to patch things together in a sloppy way and get what I want, but I would love your advice on how to be elegant. I want to grow, and I don't want to program sloppily anymore.</p>
  
  <p>Thanks a lot for your thoughts and advice.&lt;br&gt;
  -Oliver</p>