Embedded python: printing exceptions to a file?

Bjorn Pettersen BPettersen at NAREX.com
Sun Jan 5 23:05:19 EST 2003


> From: Gernot Hillier [mailto:ghillie at suse.de] 
> 
> Hi!
> 
> I use embedded python in my application and I'm really 
> enthusiastic about it 
> - the API is really well designed, thx. :-)
> 
> But now I have a small problem - I want to log errors from 
> python scripts 
> running in the embedded interpreter to a log file. 

There doesn't seem to be a direct way of getting the string that's
produced when Python prints a traceback. I'm using the function below to
gather the information into a std::string (you'll need to modify it to
use a different exception type -- NException is our class.) There are
probably better ways to do this, but this works so I haven't had time to
look at it again <wink>:

  std::string getTraceback() {
    std::string result;
    PyObject *exception, *v, *traceback;
    PyErr_Fetch(&exception, &v, &traceback);
    PyErr_NormalizeException(&exception, &v, &traceback);

    /*
      import traceback
      lst = traceback.format_exception(exception, v, traceback)
    */
    PyObject* tbstr = PyString_FromString("traceback");
    PyObject* tbmod = PyImport_Import(tbstr);
    if (!tbmod) 
      throw new NException("Unable to import traceback module. Is your
Python installed?");
    PyObject* tbdict = PyModule_GetDict(tbmod);
    PyObject* formatFunc = PyDict_GetItemString(tbdict,
"format_exception");
    if (!formatFunc) 
      throw new NException("Can't find traceback.format_exception");
    if (!traceback) {
      traceback = Py_None;
      Py_INCREF(Py_None);
    }
    PyObject* args = Py_BuildValue("(OOO)", exception, v, traceback);
    PyObject* lst = PyObject_CallObject(formatFunc, args);

    for (int i=0; i<PyList_GET_SIZE(lst); i++) {
      result += PyString_AsString(PyList_GetItem(lst, i));
    }

    Py_DECREF(args);
    Py_DECREF(lst);
    return result;
  }

> <OT>
> I just wonder if it would be wise to splitup this newsgroup 
> into some more specific subjects like (just suggestions)
[...]

This is usually brought up once a year or so and so far nothing has
changed. That doesn't mean it shouldn't change ever, but probably
implies that it will take someone with a lot of initiative and stamina
to champion it... 

-- bjorn





More information about the Python-list mailing list