I'm searching for a way to import modules from a location on the local
filesystem without the requirement of appending the parent-directory to
sys.path. Here's example-code showing the demanded interface:
imp = Importer()
imp.add_path(r'C:\pylibs')
foolib = imp.import_('foolib')
print foolib
# <module 'foolib' from 'C:\pylibs\foolib.py'>
I can think of an implementation like this, but I was wondering if it is
possible without the workaround of exchanging the sys.path variable
temporaribly.
import sys
class Importer(object):
def __init__(self):
super(Importer, self).__init__()
self.path = []
def add_path(self, path):
self.path.append(path)
def import_(self, name):
old_path = sys.path
sys.path = self.path
try:
return __import__(name, {}, {})
finally:
sys.path = old_path