How to capture stdout/stderr?
Hi, I am trying to capture stdout and stderr from Python using boost.python. I can do it using the Python C API but can't work out the correct way to do it using the boost wrappers. Using the C API I'd do something like: PyObject* pObj = Py_InitModule("stdout", my_methods); PySys_SetObject("stdout", pObj); PySys_SetObject("stderr", pObj); How should I do this with boost? Thanks Peter
At 01:08 28/08/2004 -0400, you wrote:
Hi,
I am trying to capture stdout and stderr from Python using boost.python.
Here is my, considerably low-tech, code : At init time, ----------- const std::string CatchOutput = "class StdoutCatcher:\n" "\tdef __init__(self):\n" "\t\tself.data = ''\n" "\tdef write(self, stuff):\n" "\t\tself.data = self.data + stuff\n" "\n" "import sys\n" "TheStdoutCatcher = StdoutCatcher()\n" "sys.stdout = TheStdoutCatcher\n"; Run (CatchOutput); // thin wrapper to run a snippet ----------- and then after some python code has run : ----------- using namespace boost::python; object Catcher (main_namespace ["TheStdoutCatcher"]); object CatcherData (borrowed (PyObject_GetAttrString (Catcher.ptr (), "data"))); const std::string &S = extract<std::string>(CatcherData); Output += S; // some log string Run ("sys.stdout.data=''\n"); ----------- Note I'm pretty new at this, so the only warranty is "the above didn't crash so far" :) Now that I paste it, I'm not sure about that const ref to the result of extract. hth, bert
participants (2)
-
Bert Peers -
Peter