importing specific module

Peter Hansen peter at engcorp.com
Tue Jun 17 23:51:02 CEST 2003


drs wrote:
> 
> I feel like I have seen this answered here, but I am not finding the
> discussion, so sorry if this is asked a lot.
> 
> I would like to import a specific module which may or may not be on the
> path, and because of concerns about duplicate names, changing network
> drives, and moving files, I would rather not append sys.path.  So, something
> like
> 
> >>> import('C:\\path\\to\\some\\module.py')
> 
> is what I am looking to do. imp.load_module() seems promising, but the
> documentation is going over my head so I am not sure it is appropriate.  Any
> suggestions?  Thanks,

I think you want roughly this.  It may require some tweaks from
others here to make it robust or general enough for your intended use,
but it worked roughly as-is for me.  (Not tested exactly as it appears 
here.)

def import_from_file(name, path):
    import sys, imp
    f = open(path, 'rb')
    try:
        description = ('.py', 'r', imp.PY_SOURCE)
        mod = imp.load_module(name, f, path, description)
        sys.modules[name] = mod
    finally:
        f.close()


-Peter




More information about the Python-list mailing list