我正在尝试将 python 嵌入到我的 C
代码中。所以目标是我想在 C 程序中运行 python 代码,当 python 代码完成运行时,它应该返回一个整数值给我的 C 程序。
在我的 python 代码“try.py”中,我在 python 文件末尾指定了 return 10
。
但是,我尝试了以下方法,但返回值始终为0
。为什么?
#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;
}
最佳答案
PyRun_SimpleFileEx
成功时返回 0
,出错时返回 -1
。
此内容摘自 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.
关于python - 在 C 中嵌入 Python : unable to read python return integer value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29270029/