Am 01.06.2012 05:06, schrieb Qi: > On 2012-5-31 23:01, Ulrich Eckhardt wrote: >> I can only guess what you are doing, maybe you should provide a simple >> piece of code (or, rather, one C++ piece and a Python piece) that >> demonstrates the issue. What I could imagine is that the Python >> interpreter shuts down with something it considers an unhandled >> exception, which it then prints to stdout before exiting. When >> embedding, that shouldn't happen from just calling a Python function in >> a loaded script, those should just make the error available to the C++ >> side via PyErr functions etc. > > > PyRun_SimpleString("SomeCppFunc(1, 2)"); > > SomeCppFunc is C++ function bound to Python, and in SomeCppFunc > it detects the parameter mismatch (such as it expects the first > parameter to be a string), it throws an exception. > Then the C++ binding code catches the exception, and call > PyErr_SetString to propagate it to Python.
I think this has nothing to do with the called C++ code, I guess the same happens if you call PyRun_SimpleString("raise Exception()");. > Then Python will print the error message to console. > What I want to do is to suppress the error message printing... Don't use PyRun_SimpleString() or catch the exception there. The point is that it runs the whole string as a module, like running a script from the commandline, and a pending exception on exit is then reported to stdout. What I do here is that I create a module using the C API that I register with Py_InitModule(). It contains the C++ functions exported to Python. I then load a script using PyImport_ImportModule() and use PyObject_GetAttrString(), PyCallable_Check() and PyObject_CallObject() to run the main function of that script. > Can I redirect sys.stdout in C++? Maybe, I haven't tried. Since I require a proper main function in the Python code anyway, I added a few more requirements, i.e. that it uses one of the provided C++ functions for output. I think you can simply assign "sys.stdout.write = log_string", where log_string is the provided C++ function. Uli -- http://mail.python.org/mailman/listinfo/python-list