[Python] Segmentation fault when executing a Python script in a C program?

Discussão em 'Python' iniciado por Stack, Novembro 20, 2024.

  1. Stack

    Stack Membro Participativo

    I need to execute some python and C at the same time. I tried using Python.h:

    #include <Python.h>

    int python_program(char* cwd)
    {
    char* python_file_path;
    FILE* fd;
    int run;

    python_file_path = malloc(sizeof(char) * (strlen(cwd) + strlen("src/query.py") + 1));
    strcpy(python_file_path, cwd);
    strcat(python_file_path, "src/query.py");
    fd = fopen(python_file_path, "r");

    Py_Initialize();


    run = PyRun_AnyFile(fd, "query.py"); //this part is where the bug occur i think

    Py_Finalize();

    free(python_file_path);
    }

    int main(int argc, char *argv[])
    {
    char cwd_buffer[64];


    getcwd(cwd_buffer, sizeof(cwd_buffer));
    python_program(cwd_buffer);

    return 0;
    }


    ...but there's an error with segmentation fault.

    26057 segmentation fault (core dumped) ../spotify-viewer-cli


    I isolated the Python.h part and it's the problem. So how can I execute the python file in my C program?

    Continue reading...

Compartilhe esta Página