在C中读取python的全局变量 [英] reading a global variable of python in c

查看:187
本文介绍了在C中读取python的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习如何正确使用Python/C API-我真正需要做的就是读取一个全局变量(在我的情况下是字典-但我从一个简单的整数变量开始). 使用讨论: 如何从C访问Python全局变量? 以及答案的来源: http://bytes.com/topic/python/answers/705918-c-api-embedded-python-how-get-set-named-variables 我写了这个小东西:

I am trying to learn how to use the Python/C API correctly - all I actually need to do is to read a global variable (in my case dictionary - but I'm starting with a simple integer variable). Using the discussion: How to access a Python global variable from C? and the source of the answer there: http://bytes.com/topic/python/answers/705918-c-api-embedded-python-how-get-set-named-variables I wrote this little thing:

Python代码(tryStuff.py):

Python code (tryStuff.py):

var1 = 1

var2 = ['bla', 'blalba']

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

print "end of file - tryStuff!!"

C代码(embedPythonTry.c):

C code (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程序的输出为:

The output of running this c program is:

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

这意味着Python解释器可以找到并运行正确的Python脚本,但由于某种原因,它无法读取变量(var1).

Which means the Python interpreter finds and runs the correct Python script, but somehow it can't manage to read the variable (var1).

任何人都可以发现问题-我有点迷路了.看起来最简单的情况可能是应用Python/C API,但这是行不通的. 我想念什么?

Can anyone spot the problem - I am kinda' lost already. It looks like the most simple situation that can be to apply the Python/C API, but it doesn't work. What am I missing?

推荐答案

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

You should call PyObject_GetAttrString on the result of PyImport_ImportModule. I have no idea why you think that the __main__ module should define that variable:

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

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

You should also add the check on the results, since PyImport_ImportModule can return NULL when the import fails.

这篇关于在C中读取python的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆