"dynamical" importing

J

Joerg Schuster

Hello,

I need to import modules from user defined paths. I.e. I want to do
something
like:

module_dir = sys.argv[1]

my_path = os.path.join(module_dir, 'bin', 'my_module')

from my_path import my_object

Obviously, it doesn't work this way. How would it work?

Jörg Schuster
 
F

Fredrik Lundh

Joerg said:
I need to import modules from user defined paths. I.e. I want to do
something like:

module_dir = sys.argv[1]

my_path = os.path.join(module_dir, 'bin', 'my_module')

from my_path import my_object

Obviously, it doesn't work this way. How would it work?

some alternatives:

- if you want the modules to remain imported:

try:
sys.path.insert(0, os.path.join(module_dir, "bin"))
module = __import__("my_module")
finally:
del sys.path[0]
object = module.my_object

- if you're only interested in the object:

namespace = {}
execfile(os.path.join(module_dir, "bin", "my_module" + ".py"), namespace)
object = namespace["my_object"]

</F>
 
J

John Abel

Try:

userModule = _importModule( pathToModule )

def _importModule( moduleName ):
modName = __import__ ( moduleName )
modComponents = moduleName.split( '.' )
for indivComp in modComponents[ 1: ]:
modName = getattr( modName, indivComp )

return modName

HTH,

J
 
F

Fredrik Lundh

John said:
def _importModule( moduleName ):
modName = __import__ ( moduleName )
modComponents = moduleName.split( '.' )
for indivComp in modComponents[ 1: ]:
modName = getattr( modName, indivComp )

return modName

__import__ takes a module name, not an arbitrary file name.

</F>
 
J

John Abel

Fredrik said:
John Abel wrote:


def _importModule( moduleName ):
modName = __import__ ( moduleName )
modComponents = moduleName.split( '.' )
for indivComp in modComponents[ 1: ]:
modName = getattr( modName, indivComp )

return modName

__import__ takes a module name, not an arbitrary file name.

</F>
Didn't mean to imply that it did. By pathToModule, I meant spam.ham as
in
http://localhost/documentation/Python-Docs-2.4.1/lib/built-in-funcs.html#l2h-6
( hopefully, that should explain things to the OP ).

J
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top