0

I am trying to embed python in my C code. So the objective is that I want to run a python code inside C program, and when the python code finish running, it should return a integer value back to my C program.

In my python code "try.py", I specify return 10 at the end of the python file.

However, I tried the following, but the return value is always 0. Why?

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

int main(void)
{    int sys;
     Py_Initialize();
     PyObject* PyFileObject = PyFile_FromString("try.py", "r");
     sys=PyRun_SimpleFileEx(PyFile_AsFile(PyFileObject), "try.py", 1);
     Py_Finalize();
     printf("\n\n the return value is %d\n\n",sys);
     return 0;
}
Clifford
  • 88,407
  • 13
  • 85
  • 165
andy_ttse
  • 19
  • 2
  • 6
  • 1
    It has to be because `PyRun_SimpleFileEx` returns `0` on success, think about it, a python program returning an integer that way doesn't make sens, Please post the `python` code too. [Read this](https://docs.python.org/2/c-api/veryhigh.html#c.PyRun_SimpleStringFlags) – Iharob Al Asimi Mar 26 '15 at 02:24
  • You say "_I specify `return 10` at the end of the python file._" Don't you get a `SyntaxError: 'return' outside function` there? – Armali Sep 17 '15 at 08:24

1 Answers1

0

The PyRun_SimpleFileEx returns 0 on success and -1 on error.

This was extracted from here

int PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)

Executes the Python source code from command in the main module according to the flags argument. If main does not already exist, it is created. Returns 0 on success or -1 if an exception was raised. If there was an error, there is no way to get the exception information. For the meaning of flags, see below.

Note that if an otherwise unhandled SystemExit is raised, this function will not return -1, but exit the process, as long as Py_InspectFlag is not set.

Community
  • 1
  • 1
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97