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
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