embedding
Michael P. Reilly
arcege at shore.net
Fri Aug 6 10:44:33 EDT 1999
vysteric at my-deja.com wrote:
: I've been reading through my docs for hours, and I can't seem to find an
: answer to this.. How do you create an object in the main namespace and
: how do you get the value of an object in the main namespace? Without
: using PyRun*
: thanks
: Patrick
Hi Patrick,
I'm surprised that noone has answered this before now. You will want
to first import the module, then access attributes of it.
PyObject *module__main__;
PyObject *MyName, *whom;
module__main__ = PyImport_ImportModule("__main__");
/* try:...except:...*/
if (module__main__ == NULL)
return NULL;
MyName = PyString_FromString("Arcege");
if (PyObject_SetAttrString(module__main__, "person_name", MyName) == -1) {
/* an exception */
Py_DECREF(module__main__);
Py_DECREF(MyName);
return NULL;
}
Py_DECREF(MyName);
whom = PyObject_GetAttrString(module__main__, "person_name");
if (whom == NULL) {
Py_DECREF(module__main__);
return NULL;
}
PyObject_Print(whom, stdout, Py_PRINT_RAW);
Py_DECREF(module__main__);
This is roughly equivalent to:
import __main__
__main__.person_name = "Arcege"
print __main__.person_name
I use this a good deal to get access to other modules in my own code.
But, if you mean: "How can I create an object in the global namespace?"
That is slightly different; for this you can use PyEval_GetGlobals().
This returns a dictionary, on which you can then use
PyDict_GetItemString() and PyDict_SetItemString().
-Arcege
More information about the Python-list
mailing list