-1

I'm currently working on a project that uses a C source file that has to interact with a python file (run the file and capture output) and im not exactly sure how to do it. currently the python file is run through terminal (linux) using:

python file arg1 arg2 arg3 arg4 

and i am trying to embed python into the C code to just run the file first (no output capture) using the following code:

void python() {  
    FILE * file;
    int argc;
    char * argv[5];

    argc=5;
    argv[0]="pathtofile/file";
    argv[1]="arg1";
    argv[2]="arg2";
    argv[3]="arg3";
    argv[4]="arg4";
    Py_SetProgramName(argv[0]);
    Py_Initialize();
    PySys_SetArgv(argc,argv);
    file= fopen("pathtofile/file","r");
    PyRun_SimpleFile(file,"pathtofile/file");
    PyFinalize();   
}

args1-2 are hard coded, and args3-4 are determined by the C code (just determines integer values), this is then passed to the python file where it then executes.

When running the above code i get a: TypeError: unsupported operand type(s) for + :NoneType and 'str'

Any advice from here on what could be my issue is greatly appreciated.

EDIT: I was using this as a guide as it seems to be similar to what im trying to acheive Run a python script with arguments

Community
  • 1
  • 1
EthanW05
  • 1
  • 1

1 Answers1

1

Your argc is uninitialized - did you compile with warnings enabled and warnings made into errors (-Wall, -Werror on GCC?); and your argv is not properly null-terminated. Thus your code has undefined behaviour. Anything might happen including demons flying out of your nose. The argument to fopen mode must be a string yet you pass an int (character constant) - which has another UB.

Thus at least you must do:

int argc = 5;
char *argv[] = {
    "pathtofile/file",
    "arg1",
    "arg2",
    "arg3",
    "arg4",
    0 
};
input = fopen(..., "r"); //  "r", not 'r'!

Additionally you're not checking the return values of any of these functions. Any of them may fail and with Python you should expect them to fail - including your fopen! (Please tell that they're omitted for brevity).

  • thankyou for the quickly reply, i should of mentioned that i am very new to python so now that i have some direction i can try continue from here – EthanW05 Apr 20 '16 at 05:52
  • Also relatively new to C, This was the first question i have asked so forgive me for not being as direct as i should have been. – EthanW05 Apr 20 '16 at 06:00
  • You *can* and *should* give your question *minor edits* (not changing the thing you're asking, but fixing your question), including making sure the code is an actual copy-paste of your code (that one does not even compile **anywhere** because of the `:` after PyFinalize()`. – Antti Haapala -- Слава Україні Apr 20 '16 at 06:08
  • thanks i missed that when i made the first edit. i am unable to copy the code directly due to it being for a product so i rewrote it removing the confidential information. – EthanW05 Apr 20 '16 at 06:13