1

I want to plot some data using matplotlib and a python script if a button in a Qt application is pressed. The slot which receives the signal from the startPythonButton is defined in the following way:

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);
}

The python script is defined as:

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()

When I run the Qt program and click the startPythonButton, the plot is shown normally. When I close the plot-window and click the startPythonButton again however, the Qt process receives a SIGSEGV when trying to call PyRun_SimpleFile.

Any ideas where the error could be?


So it turns out that the second fopen() call does not fail (e.g. does not return 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;
    };
}
Mantabit
  • 269
  • 1
  • 4
  • 14

1 Answers1

1

fopen is not used correctly. It returns NULL on failure. You need to replace the test if(file<0) with if(file==NULL). As it stands, you are missing the failure case.

It is advisable to provide user feedback if such an operation fails.

This answer (probably among many others) shows how to fetch more details about fopen errors.

  • Thanks for your response. However, it seems like neither the fopen() or the fclose() call fail. I checked this in the debugger. The second fopen() call seems to return a faulty filepointer which causes the SIGSEGV. I added the new code to the original post. – Mantabit Dec 17 '18 at 20:06