开发者

use Chameleon ZPT templates to write out print statements

I am using Pyramid and I know that this is probably not the preferred way to do things but it would be really cool. I have a bunch of Python scripts which print to stdout. Now I want to run these scripts as part of a request/ response in Pyramid. I mean I want to capture the stdout of the scripts and write it to the template.

The capturing stdout part is pretty easy:

开发者_JAVA技巧
import sys
sys.stdout = tbd

As far as I can see render_to_response does not support any of this:

return render_to_response(’templates/foo.pt’,
    {’foo’:1, ’bar’:2},
    request=request)

Any idea how I can get a write() operation on the template?


I might use the subprocess module to capture the stdout of the script instead of importing it and running it directly:

import StringIO
output = StringIO.StringIO()
result = subprocess.call('python', 'myscript.py', stdout=output)
value = output.get_value()

string = render(’templates/foo.pt’,
    {'value':value},
    request=request)


You could pass a StringIO.StringIO object to stdout, then also pass it to the template via the context dictionary and just call StringIO.StringIO.getvalue() at the proper times in the template:

import sys

def my_view(request):
    old_stdout = sys.stdout
    new_stdout = StringIO.StringIO()
    sys.stdout = new_stdout

    # execute your scripts

    sys.stdout = old_stdout

    return render_to_response('template/foo.pt', {'foo': 1, 'bar': 2, 'stdout': new_stdout},
        request=request)

and then in the template:

<html>
  <body>
    <!-- stuff -->
    ${stdout.getvalue()}
    <!-- other stuff -->
  </body>
</html>

You'll probably need to add a filter to make sure the text is formatted properly, or you might just create a subclass of StringIO.StringIO with an __html__ method that would render things as you see fit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜