Help: Trouble with imp.load_module

Discussion in 'Python' started by David Hirschfield, Dec 11, 2007.

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

    --
    Presenting:
    mediocre nebula.
    David Hirschfield, Dec 11, 2007
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Gabriel Genellina

    Re: Help: Trouble with imp.load_module

    Gabriel Genellina, Dec 17, 2007, in forum: Python
    Replies:
    0
    Views:
    371
    Gabriel Genellina
    Dec 17, 2007
  2. Paul Sijben
    Replies:
    1
    Views:
    374
    Christian Heimes
    Feb 1, 2008
  3. Replies:
    2
    Views:
    1,032
  4. MRAB
    Replies:
    0
    Views:
    403
  5. Iuri
    Replies:
    0
    Views:
    154
Loading...

Share This Page