Beginner's question : Embedding Python - problem with PyRun_SimpleString
Adrian Eyre
a.eyre at optichrome.com
Mon Oct 11 07:08:16 EDT 1999
> Thanks for this tip. Actually I'm running under Win32 I need to figure out
> how to redirect stderr.
Well. Here's one way to do it (n.b. I haven't tested whether this compiles):
//-------------------------------------------------------------------------
// Catch method
static PyObject* catch(PyObject* self, PyObject* args)
{
char* string;
// Check args
if (!PyArg_ParseTuple(args, "Os", &self, &string))
return NULL;
// Do something with string
my_func(string);
// And return
Py_INCREF(Py_None);
return Py_None;
}
//-------------------------------------------------------------------------
// Declare Python exports
static struct PyMethodDef catch_methods[] = {
{ "catch", catch, 1 },
{ NULL, NULL, 0 }
};
//-------------------------------------------------------------------------
// Main
void main()
{
Py_Initialise();
PyObject* catch = Py_InitModule("catch_module", catch_methods);
PyObject* catch_dict = PyModule_GetDict(catch);
PyObject* catch_func = PyDict_GetItemString(catch_dict, "catch");
PyObject* class_dict = PyDict_New();
PyObject* empty_tuple = PyTuple_New(0);
PyObject* class_name = PyString_FromString("Catch");
PyObject* catch_class = PyClass_New(empty_tuple, class_dict,
class_name);
PyObject* catch_meth = PyMethod_New(catch_func, 0, catch_class);
PyDict_SetItemString(class_dict, "write", catch_meth);
PyObject* catch_inst = PyInstance_New(catch_class, 0, 0);
PySys_SetObject("stderr", catch_inst);
Py_DECREF(class_dict);
Py_DECREF(empty_tuple);
Py_DECREF(class_name);
Py_DECREF(catch_class);
Py_DECREF(catch_meth);
Py_DECREF(catch_inst);
// Run Python code here
PyRun_SimpleString("wibble");
// Finish up
Py_Finalize();
}
> What about for the normal output of a command ?
Anything you 'print' will go to stdout.
> Do I have to redirect stdout as well ?
If you want to catch this too, then yes.
--------------------------------------------
Adrian Eyre <mailto:a.eyre at optichrome.com>
Optichrome Computer Solutions Ltd
Maybury Road, Woking, Surrey, GU21 5HX, UK
Tel: +44 1483 740 233 Fax: +44 1483 760 644
http://www.optichrome.com
--------------------------------------------
More information about the Python-list
mailing list