2016-01-08 20 views
2

我使用Boost :: Python來執行一些腳本,當發生一些錯誤時,我會在日誌窗口中顯示錯誤消息,發生錯誤。 不幸的是,我無法獲得SyntaxError的行號(以及此異常的子類,例如IndentationError)。如何使用Boost獲取SyntaxError,NameError等的Python錯誤信息

在這個答案使用代碼:

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); 

我設法讓得到p值和ptraceback非的SyntaxError異常所有的錯誤信息。

但是,對於SyntaxError,沒有回溯(ptraceback爲NULL),您可以從中獲取信息。

我需要知道行號,但我不確定是否可以使用Boost來獲取行號。

有沒有什麼辦法讓錯誤發生的行號?

只要有行號就足夠了。其他信息是不必要的(例如文件),因爲我已經有我需要的東西(錯誤類型和描述)。

回答

1

我發現,在這裏工作的方式:

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

總之,要得到行號發生語法錯誤,其中:

// 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   
}