A question on embedding python and redirecting stderr and stdout

Jesse Marlin jesse.marlin at intec-telecom-systems.com
Mon Aug 26 13:48:04 EDT 2002


Jesse Marlin <jesse.marlin at intec-telecom-systems.com> writes:

> I am embedding python in an application and would like to know
> if it is possible to redirect where python sends its output.
> I have noticed the following functions PySys_WriteStdout and
> PySys_WriteStderr, which write to stdout and stderr.  I do
> not think what I want to do is possible except to change the code
> or forking python stuff.  The reason for wanting this is so I can have
> feedback from executed scripts which is not munged in with all
> other writes to stderr or stdout.  Thanks for any help.

 > 
 > You don't say what exactly you want to do with the output,
 > but if it's any help I have done something along the lines
 > of what you say in a Qt app for Windows which uses a
 > QTextEdit widget for I/O to the Python interpreter.

Yes, this is exactly what I was looking for.  Its looks like you
are changing the output in a Python snippet.  What would have been
nice would be to have a C call to do this.  Thanks for the help!

 > 
 > Relevant portions of code are:
 > 
 > // Write python output to msgview
 > static PyObject * output(PyObject *self, PyObject *args)
 > {
 > 	char *string;
 > 	if (!PyArg_ParseTuple(args, "s", &string))
 > 		return 0;
 > 	gld::gMsgView()->write( "%s", string);
 > 	return Py_BuildValue("");
 > }
 > 
 > // Define methods available to Python
 > static PyMethodDef ioMethods[] = {
 > 	{"output", output, METH_VARARGS, "output"},
 >    {NULL, NULL, 0, NULL}
 > };
 > 
 > int main(int argc, char ** argv)
 > {
 > 	// Start up Python
 > 	Py_Initialize();
 > 
 > 	// Redirect Python output to msg window
 > 	PyObject* gld_module = Py_InitModule("gld", ioMethods);
 > 	char *code =	"class Sout:\n"
 > 			"    def write(self, s):\n"
 > 			"        output(s)\n"			
 > 			"\n"
 > 			"import sys\n"
 > 			"from code import *\n"
 > 			"from gld import *\n"
 > 			"sys.stdout = Sout()\n"
 > 			"sys.stderr = Sout()\n"
 > 			"sys.stdin  = None\n";
 > 	int r1 = PyRun_SimpleString(code);
 > 
 > The above just redirects Python stdio and stderr to the C function
 > 'output' which then writes to the QTextEdit widget.
 > 
 > HTH,
 > 
 > Keith




More information about the Python-list mailing list