Problem getting stdout redirected for embedded Python

eliot.muir at interfaceware.com eliot.muir at interfaceware.com
Fri Oct 20 14:11:54 EDT 2000


Hi,

I've been trying to embedd Python in a C application
and come to the standard problem of how to redirect the
stdout and stderr.

The approach of creating an object which implements the write command
and assigning it to the sys.stderr and sys.stdout seems to be the
right approach.  But I found that I seem to running into some
name scoping problems.  I believe it is something to do with the
way I am invoking Python using the C API.

I spent half an hour stripping everything down to the most basic
code which reproduces the problem.  This script works when invoked
from the python interpreter:

import string
print string.lower("LOWERCASE")
class myRedirect:
   def write(self, str):
      print string.lower(str)
a = myRedirect()
a.write("LOWERCASE")

Run as a script it predictably produces the output "lowercase" twice.

But embedded in my C program the script fails on the last line with the
statment "There is no variable string" indicating some type of scoping
problem.

This is the complete C code:

#include <Python.h>

int main()
{
   Py_Initialize();
   PyObject* main_module, *GlobalDict, *LocalDict;
   main_module = PyImport_ImportModule ("__main__");
   GlobalDict = PyModule_GetDict(main_module);
   LocalDict = PyDict_New();
   Py_XDECREF(main_module);

   PyRun_String("import string\n", Py_file_input, GlobalDict,
LocalDict);
   if (NULL == PyRun_String("print string.lower(\"LOWERCASE\")\n",
Py_file_input, GlobalDict, LocalDict))
   {
      PyErr_Print();
   }
   if (NULL == PyRun_String("class myRedirect:\n   def write(self,
str):\n      print string.lower(\"LOWERCASE\")\n", Py_file_input,
GlobalDict, LocalDict))
   {
      PyErr_Print();
   }
   if (NULL == PyRun_String("a = myRedirect()\n", Py_file_input,
GlobalDict, LocalDict))
   {
      PyErr_Print();
   }
   if (NULL == PyRun_String("a.write(\"LOWERCASE\")\n", Py_file_input,
GlobalDict, LocalDict))
   {
      PyErr_Print();
   }
   Py_XDECREF(LocalDict);
   Py_XDECREF(GlobalDict);

	Py_Exit(0);
   return 0;
}

I suspect it has to with my lack of understanding of the global
and local name space dictionary arguments?

Any suggestions appreciated!

Cheers,
Eliot


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list