python - 在 C 中嵌入 Python : unable to read python return integer value

标签 python c embed cross-language

我正在尝试将 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/

相关文章:

python - 使用 Python 查找 PDF 的标题

c - 如何用Visual Studio 2010开发C语言?

python - 复制 xpath 未提供正确的 xpath?

python - 以编程方式在 FUSE 中发出命令?

python - numpy linspace 返回正区间的负数

c - 十六进制数比较?

c - PAM pam_sm_close_session 没有启动

javascript - 默认情况下嵌入带字幕的 Youtube 不起作用

c - 中断处理程序是否像这样运行,运行多长时间?

c# - 在 C# 中将 Exe 文件作为嵌入式资源运行