在c中读取python的全局变量

时间:2014-07-14 08:51:56

标签: python c python-c-api

我正在努力学习如何正确使用Python / C API - 我真正需要做的就是读取一个全局变量(在我的案例中是字典 - 但我从一个简单的整数变量开始)。 使用讨论: How to access a Python global variable from C? 那里答案的来源: http://bytes.com/topic/python/answers/705918-c-api-embedded-python-how-get-set-named-variables 我写了这个小东西:

Python代码(tryStuff.py):

var1 = 1

var2 = ['bla', 'blalba']

var3 = {"3" : "Three", "2" : "Two", "1" : "One", "0" : "Ignition!"}

print "end of file - tryStuff!!"

C代码(embedPythonTry.c):

#include <python2.7/Python.h>

int main(int argc, char **argv){
  Py_Initialize();
  PyRun_SimpleString("import sys");
  PyRun_SimpleString("sys.path.append('<the absolute path of the folder in which the python file is located>')");
  PyImport_ImportModule("tryStuff");
  printf("After the import, before the addition\n");
  PyObject *mainModule = PyImport_AddModule("__main__");
  PyObject *var1Py = PyObject_GetAttrString(mainModule, "var1");
  int var1Int = PyInt_AsLong(var1Py);
  printf("var1=%d ; var1==NULL: %d\n", var1Int, var1Py==NULL);
  Py_XDECREF(var1Py);
  Py_Finalize();
  return 0;
}

运行此c程序的输出是:

end of file - tryStuff!!
After the import, before the addition
var1=-1 ; var1==NULL: 1

这意味着Python解释器找到并运行正确的Python脚本,但不知怎的,它无法设法读取变量(var1)。

任何人都可以发现问题 - 我有点儿&#39;已经失去了。它看起来像应用Python / C API的最简单的情况,但它不起作用。 我错过了什么?

2 个答案:

答案 0 :(得分:1)

您应该在PyObject_GetAttrString的结果上致电PyImport_ImportModule。我不知道您为什么认为__main__模块应该定义该变量:

PyObject *mod = PyImport_ImportModule("tryStuff");
PyObject *var1Py = PyObject_GetAttrString(mod, "var1");

您还应该添加对结果的检查,因为导入失败时PyImport_ImportModule可以返回NULL

答案 1 :(得分:1)

我知道这个问题来自很久以前,但这是给那些在谷歌搜索时偶然发现这个问题的人提供的。

OP表示他的代码行不通,但具有讽刺意味的是,他的代码对我来说比其他示例更好。(谢谢,@ et_l)

所以,答案-如何从C访问python变量-OP的代码(使用OP编写的主模块代码);

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

int main () {
  Py_Initialize();
  PyRun_SimpleString("var1 = 1");
  PyRun_SimpleString("var2 = ['bla', 'blalba']");
  PyRun_SimpleString("var3 = {'3' : 'Three', '2' : 'Two', '1' : 'One', '0' : 'Ignition!'}");
  PyRun_SimpleString("print('end of file - tryStuff!!')");

  PyObject *mainModule = PyImport_AddModule("__main__");
  PyObject *var1Py = PyObject_GetAttrString(mainModule, "var1");
  int c_var1 = PyLong_AsLong(var1Py);
  printf("var1 with C: %d\n", c_var1);

  Py_Finalize();
  return 0;
}
相关问题