Gary Herron <gh*****@islandtraining.comwrote:
Andre Poenitz wrote:
>Hi all.
Is there a way to load a module given a full path to the module
without extending sys.path first?
The standard module named "imp" can help you with this.
Thank you. I got stuck on
http://docs.python.org/api/importing.html
(as I need it to be called from C(++)) and found no way to specify a path there
[and there aren't too many cross references in the python docs *sigh*]
I have now something similar to
class CPyObject
{
public:
explicit CPyObject(PyObject * pObject) : m_pObject(pObject) { /*Check();*/ }
~CPyObject() { Py_XDECREF(m_pObject); }
operator PyObject *() { return m_pObject; }
private:
CPyObject(const CPyObject &); // intentionally not implemented
void operator=(const CPyObject &); // intentionally not implemented
PyObject * m_pObject;
};
static PyObject * LoadModule(const char * mod, const char * path)
{
CPyObject pyImpModule ( PyImport_Import(PyString_FromString("imp")) );
CPyObject pyImpFindModuleFunc ( PyObject_GetAttrString(pyImpModule, "find_module") );
CPyObject pyImpFindModuleArgs ( Py_BuildValue("s[s]", mod, path) );
CPyObject pyImpFindModuleRes ( PyObject_CallObject(pyImpFindModuleFunc, pyImpFindModuleArgs) );
CPyObject pyImpLoadModuleFunc ( PyObject_GetAttrString(pyImpModule, "load_module") );
CPyObject pyImpLoadModuleArgs ( Py_BuildValue("sOOO",
mod,
PyTuple_GetItem(pyImpFindModuleRes, 0),
PyTuple_GetItem(pyImpFindModuleRes, 1),
PyTuple_GetItem(pyImpFindModuleRes, 2)
));
return PyObject_CallObject(pyImpLoadModuleFunc, pyImpLoadModuleArgs);
}
which seems to do what I want even if it looks a bit too verbose for my taste and I
don't know whether I go the reference counting right.
Thanks for the hint,
Andre'