Help: Trouble with imp.load_module

D

David Hirschfield

I'm not entirely sure what's going on here, but I suspect it's related
to my general lack of knowledge of the python import internals.

Here's the setup:

module: tester.py:
-----------------
import imp
def loader(mname, mpath):
fp, pathname, description = imp.find_module(mname,[mpath])
try:
m = imp.load_module(mname, fp, pathname, description)
finally:
if fp:
fp.close()
return m

module = loader("testA","/path/to/testA/)
print module.test_func("/path/to/something")

module = loader("test.B","/path/to/test.B/")
print module.test_func("/path/to/something")
------------------


module: testA.py:
---------------
def test_func(v):
import os
return os.path.exists(v)
---------------

module: test.B.py:
---------------
def test_func(v):
import os
return os.path.exists(v)
---------------


Okay, so modules "testA.py" and "test.B.py" are functionally identical,
except for the name of the module files themselves, and this is the
important part. The tester.py module is a really simple rig to run
"imp.load_module" on those two files.

You should get no problem running the first test of module "testA.py"
but you should get a traceback when attempting to run the second module
"test.B.py":

Traceback (most recent call last):
File "tester.py", line 15, in ?
print module.test_func("/path/to/something")
File "./test.B.py", line 2, in test_func
import os
File "/usr/lib/python2.4/os.py", line 131, in ?
from os.path import curdir, pardir, sep, pathsep, defpath, extsep,
altsep
ImportError: No module named path


So this must have something to do with the "." in the name of module
"test.B.py" but what is the problem, exactly? And how do I solve it? I
will sometimes need to run load_module on filenames which happen to have
"." in the name somewhere other than the ".py" extension. Is the
find_module somehow thinking this is a package?

Any help would be appreciated,
-Dave
 

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,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top