pythoncexecvp

Running a Python program from a C program using system()


I am tasked with creating a C program that writes a python program (which prints "hello world") and executes it.

I have completed the first part (writing the python program to a file) but when I try to execute the python program from C, nothing happens. I directly tested the created file and it has the expected input so I am likely doing something wrong when attempting to execute the python program.

I am attempting to use system() in order to execute the python program:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main() {
        FILE *pfile;
        pfile = fopen("execute.py", "w");
        fprintf(pfile, "print(\"hello world\")");
        int system(const char *command);
        system("python3 execute.py");
        return 0;
}

Solution

  • As the comments suggest,

    fclose(pfile);
    

    fixes the issue