Wouter van Marle
wouter at squirrel-systems.com
Thu May 19 03:28:43 EDT 2005
On Thu, 2005-05-19 at 01:52 -0400, Graham Dumpleton wrote: > Wouter van Marle wrote .. > > def get_source(filename): > > dir, fname = os.path.split(filename) > > dir += "/" > > pycode = _psp.parse(fname, dir).splitlines() > > pycode = [s.rstrip() for s in pycode] > > for line in pycode: > > left = line.replace("\t", " "*4) > > result += left+"\n" > > return result > > This may only work for an indenting style where tabs are used. At least > the substitution of tabs with 4 spaces looks dangerous to me in that it > could screen up indenting of code. You would also be changing tabs > that may be present in literal strings. Why did you feel you needed to > do these changes. Agreed, is not necessary. I had it in because it is used as such in the psp module for html formatting (and later for debugging: the text shows a bit nicer). Is not necessary. > > def get_html(filename, vars={}): > > code = get_source(filename) > > lines = code.splitlines() > > code = 'html = ""\n' > > for l in lines: > > l = l.replace("req.write(", "html +=").replace(",0)", "") > > code += l+"\n" > > global_scope = globals().copy() > > global_scope.update(vars) > > html = "" > > l = locals() > > try: > > exec code in global_scope, l > > except: > > et, ev, etb = sys.exc_info() > > raise et, ev, etb > > return l["html"] > > Actually modifying the source code seems a bit messy to me. You could > still use the "req" wrapper class hack I suggested before, or if you know > the PSP page never actually references the "req" object explicitly, you > could pass an instance of StringIO into it and call it "req" and it should just > work. This would avoid having to pass in locals(). For the purposes of > what you are doing, there is probably no point even copying globals as > it may not give you anything you need anyway. You could almost just > use "exec code in vars". Looks like a more elegant solution indeed. I was a bit stuck on the req object part, not knowing well enough what it is and what could be passed instead. The goal was simply to get a string with the html code out of it. Ah well, another python trick learnt :) > > def get_html(filename, vars={}): > code = get_source(filename) > vars = vars.copy() > vars["req"] = StringIO.StringIO() > try: > exec code in vars > except: > et, ev, etb = sys.exc_info() > raise et, ev, etb > return vars["req"].getvalue() > > > Graham > > |