2

I am using Boost::Python to execute some scripts and when some some errors occur , I show the error messages in a log window with the line where the error happened. Unfortunately, I don't manage to get the line number for SyntaxError (and subclasses of this exception, such as IndentationError).

Using the code in this answer:

https://stackoverflow.com/a/1418703/5421357

PyObject *ptype, *pvalue, *ptraceback;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
//pvalue contains error message
//ptraceback contains stack snapshot and many other information
//(see python traceback structure)

//Get error message
char *pStrErrorMessage = PyString_AsString(pvalue);

I managed to get the get all the error information from pvalue and ptraceback for non SyntaxError exceptions.

However, in the case of a SyntaxError, there's no traceback (ptraceback is NULL) from which you can get the information.

I need to know the line number, but I'm not sure if it's possible to get it with Boost.

Is there any way to get the line number where the error happened?

It would be enough for me to have the line number. The other information is not necessary (e.g. File) since I already have what I need (error type and description).

Community
  • 1
  • 1
manujcm
  • 163
  • 11

1 Answers1

0

I found a way that works here:

https://stackoverflow.com/a/16806477/5421357

In short, to get the line number where the Syntax Error occurred:

// Init code here ...

PyObject *res = PyRun_String(script_source,Py_file_input,main_dict,main_dict);      
if(res == NULL)
{
    PyObject *ptype = NULL, *pvalue = NULL, *ptraceback = NULL;
    PyErr_Fetch(&ptype,&pvalue,&ptraceback);
    PyErr_NormalizeException(&ptype,&pvalue,&ptraceback);

    char *msg, *file, *text;  
    int line, offset;  

    int res = PyArg_ParseTuple(pvalue,"s(siis)",&msg,&file,&line,&offset,&text);

    PyObject* line_no = PyObject_GetAttrString(pvalue,"lineno");
    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);  // Line number        
}
Community
  • 1
  • 1
manujcm
  • 163
  • 11