1

I'm using cgitb (python 2.7) to create html documents server end. I have on file that does a bunch of query and then produces html. I'd like to be able to link just the html so if I could print the html to a new file and link that that, it would work.

Is there a way to get the html the page will generate at the end of processing so that I can put it in a new file without keeping track of everything I've done so far along the way?

Edit: Found a snipped here: https://stackoverflow.com/a/616686/1576740

class Tee(object):
    def __init__(self, name, mode):
        self.file = open(name, mode)
        self.stdout = sys.stdout
        sys.stdout = self
    def __del__(self):
        sys.stdout = self.stdout
        self.file.close()
    def write(self, data):
        self.file.write(data)
        self.stdout.write(data)

You have to call it after you import cgi as it overrides stdout in what appears to be a less friendly way. But works like a charm.

I just did import cgi;....... Tee(filname, "w") and then I have a link to the file.

Community
  • 1
  • 1
WorruB
  • 111
  • 1
  • 5

2 Answers2

1

From the Python Documentation

Optionally, you can save this information to a file instead of sending it to the browser.

In this case you would want to use

cgitb.enable(display=1, logdir=directory)
MWB
  • 171
  • 6
  • This only seems to claim to print the tracebacks. It also isn't working for me. I'm doing cgitb.enable(1, '/tmp/test.html') and it isn't doing anything it seems, even on an error exit. – WorruB Aug 21 '12 at 17:58
  • The directory, not the file how are you using cgitb on non-error exits? – MWB Aug 21 '12 at 18:01
  • I don't think so. How do I set it up for that? – WorruB Aug 21 '12 at 18:14
  • So cgitb does error reporting, if your program works fine then cgitb never gets handled. Perhaps you would like to tee your stdout? – MWB Aug 21 '12 at 18:21
  • This turned out to do exactly what I wanted: http://stackoverflow.com/a/616686/1576740 – WorruB Aug 21 '12 at 19:15
0
import cgitb
import sys

try:
    ...
except:
    with open("/path/to/file.html", "w") as fd:
        fd.write(cgitb.html(sys.exc_info()))
azmeuk
  • 4,026
  • 3
  • 37
  • 64