这是在 http://www.gamedev.net 上看到有人提类似的问题
原主题:http://www.gamedev.net/community/forums/topic.asp?topic_id=491813
名叫 SiCrane Staff 的老外回复内容如下:
#include <string>
#include <boost/shared_ptr.hpp>
#include <boost/python.hpp>
#include <windows.h>
class PyInitializer {
public:
PyInitializer() { Py_Initialize(); }
~PyInitializer() { Py_Finalize(); }
private:
PyInitializer(const PyInitializer &);
PyInitializer & operator=(const PyInitializer &);
};
int main(int argc, char* argv[]) {
PyInitializer py;
try {
PyRun_SimpleString("import cStringIO");
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.stderr = cStringIO.StringIO()");
// stuff that might raise a Python exception
boost::python::import("my_script"); // if my_script doesn't exist
} catch (boost::python::error_already_set) {
PyErr_Print();
boost::python::object sys(
boost::python::handle<>(PyImport_ImportModule("sys"))
);
boost::python::object err = sys.attr("stderr");
std::string err_text = boost::python::extract<std::string>(err.attr("getvalue")());
MessageBox(0, err_text.c_str(), "Python Error", MB_OK);
}
return 0;
}