【问题标题】:SIGSEGV after running a Python script for 2nd time第二次运行 Python 脚本后的 SIGSEGV
【发布时间】:2018-12-16 14:36:10
【问题描述】:

如果按下 Qt 应用程序中的按钮,我想使用 matplotlib 和 python 脚本绘制一些数据。从startPythonButton接收信号的槽定义如下:

void MainWindow::on_wdgt_startPython_clicked()
{
    FILE* file;
    Py_Initialize();
    file=fopen("/home/user/test.py","r");
    if(file<0){
        Py_Finalize();
        return;
    }
    PyRun_SimpleFile(file,"/home/user/test.py");
    Py_Finalize();
    fclose(file);
}

python脚本定义为:

import matplotlib.pyplot as plt
import numpy as np

x=np.linspace(0,2*np.pi,100)
y=np.sin(x)

plt.plot(x,y)
plt.show()

当我运行 Qt 程序并单击 startPythonButton 时,绘图正常显示。但是,当我关闭绘图窗口并再次单击 startPythonButton 时,Qt 进程在尝试调用 PyRun_SimpleFile 时会收到一个 SIGSEGV。

有什么想法可能是错误吗?


所以事实证明第二个 fopen() 调用没有失败(例如不返回 NULL):

void MainWindow::on_wdgt_startPython_clicked()
{
    FILE* file;
    Py_Initialize();
    file=fopen("/home/user/test.py","r");
    if(file==NULL){
        std::stderr << "Failed to open file." << std::endl;
        Py_Finalize();
        return;
    }
    PyRun_SimpleFile(file,"/home/user/test.py");
    Py_Finalize();
    if(fclose(file)!=0){
        std::stderr << "Failed to close file." << std::endl;
        return;
    };
}

【问题讨论】:

    标签: python-3.x qt segmentation-fault


    【解决方案1】:

    fopen 使用不正确。失败时返回NULL。您需要将测试if(file&lt;0) 替换为if(file==NULL)。就目前而言,您错过了失败案例。

    如果此类操作失败,建议向用户提供反馈。

    This answer(可能还有很多其他)展示了如何获取有关fopen 错误的更多详细信息。

    【讨论】:

    • 感谢您的回复。但是,似乎 fopen() 或 fclose() 调用都没有失败。我在调试器中检查了这个。第二个 fopen() 调用似乎返回了导致 SIGSEGV 的错误文件指针。我将新代码添加到原始帖子中。
    猜你喜欢
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多