Import and path problem

Tung Wai Yip tungwaiyip at yahoo.com
Sat Jun 14 00:39:43 EDT 2003


I was using import in these two different styles. They worked the same
for me.

-----------------------------

import m
def foo():
    m.bar()

-----------------------------

def foo():
    import m
    m.bar()

-----------------------------

Problem arise when I start the script from an arbitrary directory. It
is easy enough for me to chdir() back to the script directory

    pathname = os.path.dirname(sys.argv[0])
    abspath = os.path.abspath(pathname)
    os.chdir(abspath)

However I find that the first style of import works alright. While the
second style of import give this error

    ImportError: No module named m

It there a semantic difference on where you import? Why does the
second one fails?

Also it only fails for user modules. System modules are OK.

Wai yip






More information about the Python-list mailing list