调用Py_Initializ时防止程序崩溃

2024-04-26 04:18:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我将在一些独立的应用程序中嵌入python,因此我有以下代码:

#include <Python.h>

wchar_t* AssemblyName = NULL;

bool InitPython()
{
    Py_SetPath(L".\\Lib;.\\Lib.zip");

    if (AssemblyName == NULL && (AssemblyName = Py_DecodeLocale("My.Python.dll", NULL)) == NULL)
        return false;

    Py_SetProgramName(AssemblyName);
    Py_Initialize();

    return true;
}

void ReleasePython()
{
    if (AssemblyName != NULL)
    {
        Py_Finalize();
        PyMem_RawFree(AssemblyName);
        AssemblyName = NULL;
    }
}

int main(int argc, char *argv[])
{
    InitPython();
    PyRun_SimpleString("from time import time,ctime\nprint('Today is', ctime(time()))\n");
    ReleasePython();
    return 0;
}

注意,我使用的是python库的相对路径。所以问题是如果文件夹中没有这样的路径,程序就会崩溃,而不是以某种方式将错误返回给调用方。有什么方法可以钩住python错误处理吗?在


Tags: 代码py应用程序returnifincludetimelib