Dynamic loading of module with explicit file path

T

Tim Johnson

FYI: Using python 2.6 on ubuntu 10, backward compatibilty to 2~
needed. Self-employed programmer 24 years. Python 9 years,
part-time.

I'm not addressing an existing problem, but looking for ideas that
might help me to do some upgrading (if needed).

I'd like to solicit comments on the following methods for
dynamically loading a module from an explicit file path.
Code is all untested!

## 1 :: Go there and get it.
import sys,os
def my_import(module_name,path):
cwd = os.getcwd()
os.chdir(path)
if sys.path[0] != "":
sys.path.insert(0,"")
module = __import__(module_name)
os.chdir(cwd)
return module
## 2 :: temporarily modify sys.path, no dir change
import sys
def my_import(module_name,path):
sys_path = sys.path
sys.path.insert(0,path)
module = __import__(module_name)
sys.path = sys_path
return module
## 3 :: use the imp module
import imp
def my_import(module_name,path):
fp, pathname, description = imp.find_module(module_name,[path])
module = imp.load_module(module_name, fp, pathname, description)
return module

TIA
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,234
Latest member
SkyeWeems

Latest Threads

Top