I am using the python API for C/C++ and I would like to retrieve the line number in case of a NameError.
I followed the instructions found within the question bellow:
How to retrieve filename and lineno attribute of SyntaxError
and I wrote the following code:
PyObject *ptype = NULL, *pvalue = NULL, *ptraceback = NULL;
PyObject *comp = NULL, *eval = NULL;
char code[] = {"A=undef_var"};
comp = Py_CompileString(code, "", Py_file_input);
if (comp) {
eval = PyEval_EvalCode(comp, PyEval_GetBuiltins(), NULL);
}
if (!comp || !eval) {
PyErr_PrintEx(1); // inside this function the PyErr_Fetch(ptype, pvalue, ptraceback) is called
// retrieve the information gained from PyErr_Fetch() called inside PyErr_PrintEx(1)
pvalue = PySys_GetObject("last_value");
ptype = PySys_GetObject("last_type");
ptraceback = PySys_GetObject("last_traceback");
PyErr_NormalizeException(ptype, pvalue, ptraceback);
PyObject* line_no = PyObject_GetAttrString(pvalue,"lineno");
if (line_no) {
PyObject* line_no_str = PyObject_Str(line_no);
PyObject* line_no_unicode = PyUnicode_AsEncodedString(line_no_str,"utf-8", "Error");
char *actual_line_no = PyBytes_AsString(line_no_unicode);
}
}
The code above returns the correct line number, in case the python code contains a SyntaxError (e.g. for a simple python code like "A="), but in case of a NameError the line number is not set correctly to the pvalue object (e.g. for the python code: "A=undefined_var").
Any ideas how can I solve this problem?