【问题标题】:How to get the error message when PyRun_AnyFile failedPyRun_AnyFile 失败时如何获取错误消息
【发布时间】:2022-01-04 14:19:43
【问题描述】:

我正在尝试使用 PyRun_AnyFile 将 python 嵌入到我的 c++ 项目中。

这是我的 python 脚本:

import aaa

if __name__ == "__main__":
    print("Here")

这是我的 C++ 代码:

const char pFile[] = "C:\\testing.py";
FILE* fp = _Py_fopen(pFile, "r");
int ret = PyRun_AnyFile(fp, pFile);

我收到这样的错误消息:

Traceback (most recent call last):
  File "C:\testing.py", line 1, in <module>
    import aaa
ModuleNotFoundError: No module named 'aaa'

这是意料之中的。 我想问一下我是如何在代码中得到上述错误信息并重定向到其他错误文件的。

我试过了:

PyObject* ptype, * pvalue, * ptraceback;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
Py_ssize_t string_len = 0;
std::wcout << std::wstring(PyUnicode_AsWideCharString(pvalue, &string_len)) << std::endl;

或:

PyErr_Print();

但这并不成功。

【问题讨论】:

    标签: python c++


    【解决方案1】:

    前段时间我也遇到过类似的问题。我以这种方式解决了错误的读取。您必须在认识到脚本执行出错后执行此代码。

    PyRun_SimpleString("import traceback, sys");
    PyRun_SimpleString("trace = ''.join(traceback.format_exception(sys.last_type, sys.last_value, sys.last_traceback))");
    PyObject *mainModule = PyImport_AddModule("__main__");
    if (PyObject_HasAttrString(mainModule, std::string("trace").c_str())) {
        PyObject *var = PyObject_GetAttrString(mainModule, std::string("trace").c_str());
        if (PyUnicode_Check(var)) {
            std::string errMsg = (std::string) PyUnicode_AsUTF8(var) + "\n";
            std::cout << errMsg;
        }
    }
    

    【讨论】:

    • 谢谢,我试试
    • 你试过了吗?
    • 我试过了,但这对我不起作用。然后我重定向脚本中的路径sys.stderr = open(os.path.join(pathlib.Path(__file__).parent.resolve(), os.path.basename(__file__) + "_" + datetime.now().strftime("%Y%m%d_%H%M%S") + "_stderr" + ".log"), "w")
    猜你喜欢
    • 2013-06-24
    • 1970-01-01
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-14
    • 2015-11-21
    • 1970-01-01
    相关资源
    最近更新 更多