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 "<BR>" instead of "\n").
My cgi_main works by calling my real_main; there are a lot of options to process and it was bad design to do that multiple times. But since real_main calls print, I don't know how to change "\n" to "<BR>" post hoc.
I could easily change all instances of print to go to a tempfile and then dump that at the end, but it seems inelegant to change the existing command line version so much.
One option is to have real_main 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.
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 reform argument.
Here is an example of how I thought this class and function could work:
class cgi_tools:
def init(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', '
')),
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 ''
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.
I tried to use insepct to print the source code of print, but I couldn't do that!
print sys.out.print:
import inspect
print inspect.getsource(print) # this does not work!
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.
Thanks a lot for your thoughts and advice.<br> -Oliver