Gary Herron <gh*****@island training.comwro te:
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(PyObj ect * pObject) : m_pObject(pObje ct) { /*Check();*/ }
~CPyObject() { Py_XDECREF(m_pO bject); }
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(cons t char * mod, const char * path)
{
CPyObject pyImpModule ( PyImport_Import (PyString_FromS tring("imp")) );
CPyObject pyImpFindModule Func ( PyObject_GetAtt rString(pyImpMo dule, "find_modul e") );
CPyObject pyImpFindModule Args ( Py_BuildValue(" s[s]", mod, path) );
CPyObject pyImpFindModule Res ( PyObject_CallOb ject(pyImpFindM oduleFunc, pyImpFindModule Args) );
CPyObject pyImpLoadModule Func ( PyObject_GetAtt rString(pyImpMo dule, "load_modul e") );
CPyObject pyImpLoadModule Args ( Py_BuildValue(" sOOO",
mod,
PyTuple_GetItem (pyImpFindModul eRes, 0),
PyTuple_GetItem (pyImpFindModul eRes, 1),
PyTuple_GetItem (pyImpFindModul eRes, 2)
));
return PyObject_CallOb ject(pyImpLoadM oduleFunc, pyImpLoadModule Args);
}
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'