|
Wouter van Marle
wouter at squirrel-systems.com
Thu May 19 03:41:58 EDT 2005
And a little bit of fiddling later I come to this result: psp2html;
direct. I don't see the need of capturing the in-between Python code
anyway. As such it runs and appears pretty robust, without scary handler
hacks that I don't really understand.
Thanks Graham for the further input and advice.
from mod_python import _psp
import os
import sys
import StringIO
def psp2html (filename, vars={}):
dir, fname = os.path.split(filename)
dir += "/"
# produce usable python code using the psp parser.
pycode = _psp.parse(fname, dir).splitlines()
pycode = [s.rstrip() for s in pycode]
code = ""
# as req.write() for a real request object works a little different
# than the req.write we use here, we have to change the code a
# little bit.
for s in pycode:
code += s.replace(",0)", ")")+"\n"
vars["req"] = StringIO.StringIO()
try:
exec code in vars
except:
et, ev, etb = sys.exc_info()
raise et, ev, etb
return vars["req"].getvalue()
Wouter.
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.
>
> > 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".
>
> 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
>
>
|