newbie question: retrieving values of variables through C API

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu May 17 21:27:27 EDT 2007


En Thu, 17 May 2007 16:37:53 -0300, <joshusdog at gmail.com> escribió:

> I've got an application that embeds the Python interpreter. I have the
> following command in my code:
>
>    PyRun_SimpleString("a = \"hello\"");
>
> My question is, what is the C API function call for retrieving the
> value of the variable "a"?

The code is run in the context of the __main__ module. So you could do  
something like this:

	PyObject *m, *d, *v, *value;
	m = PyImport_AddModule("__main__");
	if (m == NULL)
		return -1;
	d = PyModule_GetDict(m);
	value = PyDict_GetItemString(d, "a")

(The code above is mostly copied from PyRun_SimpleStringFlags)
You may find other variants of PyRun_XXX more convenient to use.

-- 
Gabriel Genellina




More information about the Python-list mailing list