Best way to capture output from an exec'ed (or such) script?

Gabriel Genellina gagsl-py2 at
Fri Aug 3 01:32:23 CEST 2007

En Thu, 02 Aug 2007 16:48:06 -0300, <exscape at> escribió:

> In any case. I've added some minor scripting support, so that you can
> write dynamic pages in Python. To do this, I use execfile(), and pass
> the script a dictionary with some basic variables. The script then
> sets a "ret" variable that's sent back to the browser. That's some
> major ugliness right there! If I do a "print" inside the script, then
> it'll end up on the server console. I want it to end up in the web
> browser.

If `print` were a function, this would be easy: just provide a replacement  
into the dictionary you pass to the script. But print is a statement, and  
this becomes a bit harder.

If your web server only processes a single request at a time, you can  
replace sys.stdout (and perhaps sys.stderr) with a suitable object having  
a write() function: a true open file, or a StringIO instance, or even a  
custom object that collects "printed" lines into a list.

If your web server is multithreaded (or you use some other way to process  
many simultaneous requests) you have to be more careful - remember that  
sys.stdout is global, you must find a way to distinguish between output  
 from different processes all going into the same collector.

Gabriel Genellina

More information about the Python-list mailing list