Import and path problem

vincent wehren v.wehren at home.nl
Sat Jun 14 09:06:35 CEST 2003


"Tung Wai Yip" <tungwaiyip at yahoo.com> schrieb im Newsbeitrag
news:949lev437d4ubu0mp74go0nbb4sut6tfnp at 4ax.com...
> 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?

Frankly, I would expect both to fail. So I don't know...
>
> Also it only fails for user modules. System modules are OK.

The system modules are all in sys.path

Try adding :

    import sys
    sys.path.append('.')

to the script your executing.

Any user modules that live in the same directory as the module you are
executing should now import
o-k, irrespective of from where you are executing (i.e. what the cwd is).


Regards,
Vincent Wehren




>
> Wai yip
>
>






More information about the Python-list mailing list