[C++-sig] How to capture stdout/stderr?
Bert Peers
bert.peers at chello.be
Sat Aug 28 15:01:41 CEST 2004
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
More information about the Cplusplus-sig
mailing list