Altering 'print'/mod_python
Jeff Davis
jdavis at empires.org
Tue May 15 00:19:01 EDT 2001
Thanks for the help. I found out that sys.__stdout__ holds the original
stdout, so I can use that rather than a temp variable:
import sys
sys.stdout = foo
...
sys.stdout = sys.__stdout__
Thanks,
Jeff
Remco Gerlich wrote:
> Jeff Davis <jdavis at empires.org> wrote in comp.lang.python:
>> I have a webserver running mod_python and I would like it to
>> execute
>> python scripts (kind of like mod_perl or php). I basically made the
>> python handler script call execfile(req.filename). I am not sure this is
>> the best method.
>> Anyway, when inside the python script that is called by execfile
>> you
>> have to use req.write() to print stuff. Is there a way to access the
>> print statement directly so that when someone says print it calls
>> req.write rather than printing to a file object?
>>
>> Any advice here would be appreciated, I am certainly not
>> confident
>> that I am on the right track.
>
> Redirect stdout, like this:
>
> try:
> import sys
> oldstdout = sys.stdout
> sys.stdout = req
> execfile(req.filename)
> finally:
> sys.stdout = oldstdout
>
> Print calls sys.stdout.write, which is now redirected to req.write. The
> try: finally: is necessary to make sure the old stdout is reinstated, even
> if an exception occurs.
>
> That would work. I don't know how sensible using execfile is, either.
>
More information about the Python-list
mailing list