python - Qt项目中调用Python脚本时如何避免Segmentation fault

标签 python c++ pyqt

我正在尝试在 C++ 下调用 Python 中的函数。

这是我的尝试:

void myFuncion()
{
    PyObject* fExportar = nullptr;
    PyObject* modulo = nullptr;
    PyObject* pName = nullptr;
    const char *scriptDirectoryName = "path/of/my/pyfile";
    Py_Initialize();
    PyObject *sysPath = PySys_GetObject("path");
    PyObject *path = PyUnicode_FromString(scriptDirectoryName);
    int result = PyList_Insert(sysPath, 0, path);
    if (result == 0 )//0 if ok, -1 if error
    {
        pName = PyUnicode_FromString("exportarXLS");//exportarXLS.py
        modulo = PyImport_Import(pName);
        Py_DECREF(path);
        if (modulo)
        {           
                fExportar = PyObject_GetAttrString(modulo, "exportar");//it crahs here
                Py_DECREF(modulo);                
                if (fExportar)
                {
                     //call the function
                }
            }        
    }
    else
    {
        PyErr_Print();
    }
    Py_Finalize();
}
}

问题是如果 python 脚本有任何错误的 import,我的 C++ 程序就会崩溃。在这种情况下,我怀疑我试图使用无效版本的 PyQt4。

这是模块:(exportarXLS.py)

#!/usr/bin/python3

from PyQt4 import QtCore, QtGui, QtSql

def exportar():
    print ("hello, I am probing")

现在我的问题:

现在我开始探索开发加载 python 插件的函数的步骤,我想知道如果有人想添加错误的 import

脚本,我将如何避免崩溃

我也尝试过将有问题的行包含在 try/catch block 中,但它不起作用。

编辑:

我忘了说它只发生在我的 Qt 项目中 如果我尝试以此运行我的函数,我可能会在加载模块时遇到错误,但它不会崩溃。 我已经编辑了标题

最佳答案

Duck 胶带解决方案:

void signal_handler(int signal)
{
  std::cout << "Usefull information" std::endl; 
  exit(1);
}
...
std::signal(SIGSEGV, signal_handler);

文档:https://en.cppreference.com/w/cpp/utility/program/signal

我认为这种解决方案应该只在调试时使用

关于python - Qt项目中调用Python脚本时如何避免Segmentation fault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55394620/

相关文章:

python - 是否有标准的 Python 数据结构可以使事物保持有序?

c++ - 在类定义之外定义显式特化类的成员函数

python - 如何使用 PySide 向 QTableWidget 添加数据

python - Selenium + Python + Chrome : simultaneously add_experimental_option and set desired_capabilities

python - 使用 pandas 选择 csv 文件中的值并计算它们

python - 如何使用 Pyrebase 获取具有特定子键的数据

c++ - while(cin) 循环 DOUBLE 显示

c++ - 为什么这段代码在实际的 BCM2837 (pi 3) 上运行时会挂起,但在 qemu 上运行良好

python - 使用 py2app 捆绑 PyQt5 应用程序 : keep getting "Abort trap: 6" error

python - PyQt:最大化窗口时如何防止处理多个调整大小事件?