Python3 获取异常的信息和traceback(实现类似PyErr_Print功能)

void fetch_error()
{
	PyObject *type = NULL, *value = NULL, *traceback = NULL;


	PyErr_Fetch(&type, &value, &traceback);

	if (type)
	{
		std::cout << PyExceptionClass_Name(type) << ": ";
	}

	if (value)
	{
		PyObject *line = PyObject_Str(value);
		if (line && (PyUnicode_Check(line)))
			std::cout << PyUnicode_1BYTE_DATA(line);
	}

	std::cout << std::endl;

	if (traceback)
	{
		for (PyTracebackObject *tb = (PyTracebackObject *)traceback;
			NULL != tb;
			tb = tb->tb_next)
		{
			PyObject *line = PyUnicode_FromFormat("  File \"%U\", line %d, in %U\n",
				tb->tb_frame->f_code->co_filename,
				tb->tb_lineno,
				tb->tb_frame->f_code->co_name);
			std::cout<< PyUnicode_1BYTE_DATA(line)<




你可能感兴趣的:(Python)