469,282 Members | 2,008 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,282 developers. It's quick & easy.

Loading module via full path

Hi all.

Is there a way to load a module given a full path to the module
without extending sys.path first?

Andre'

Aug 21 '06 #1
3 1710
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?

Andre'

The standard module named "imp" can help you with this.

Gary Herron
Aug 21 '06 #2
Andre Poenitz <an***@svn2.wasy.dewrote:
Hi all.

Is there a way to load a module given a full path to the module
without extending sys.path first?
Ok. imp.find_module() and imp.load_module() seem to do what I need.

Andre'
Aug 22 '06 #3
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'
Aug 22 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.

By using this site, you agree to our Privacy Policy and Terms of Use.