开发者

importing files residing in an unrelated path

Consider I have a directory called root that has two directories: x and y. I have a module file that resides in x, let us call that test.py. Now in y, I have a module that needs to call test.py

I am doing a simple:

from x import tes开发者_开发技巧t

And it works. I was wondering, how this works?

EDIT: How it works, as in there was no __init__.py file in x, but yet from y I was able to call a module from there.


It doesn't. You, or your operating system, or your Python site startup scripts, have modified PYTHONPATH.

14:59 jsmith@upsidedown pwd
/Users/jsmith/Test/Test2/root

14:59 jsmith@upsidedown cat x/test.py
def hello():
  print "hello"

14:59 jsmith@upsidedown cat y/real.py
#!/usr/bin/python
from x import test
test.hello()

14:59 jsmith@upsidedown y/real.py
Traceback (most recent call last):
  File "y/real.py", line 3, in <module>
    from x import test
ImportError: No module named x


Because there's a path to it. Try this:

import sys
print sys.path

That should output all the places python uses as the starting direcctory to resolve module locations. So for example, if root is actually in /home/PulpFiction/root (or C:\Documents and Settings\PulpFiction\My Documents\root on windows), you'll see something like this:

['', '/usr/local/lib/python2.6/dist-packages', *more stuff*, '/home/PulpFiction/root']

or on windows:

['', 'C:\\python26\\site-packages', *more stuff here*, 'C:\Documents and Settings\PulpFiction\My Documents\root']

There are a few ways sys.path can be set (that I know of):

  1. The directory you run the script from
  2. Environment variable (PYTHONPATH to be exact)
  3. Windows Registry (on windows only obviously)
  4. Manually appending a path to the sys.path variable yourself in the code

I'm guessing the reason it work for you is you have a script in root (let's say main.py), and that script end up importing from both x and y. Since you're running the script in the root directory it's added to the python path, which allows from x import test to work.

EDIT

There's no __init__.py eh? You sure there isn't an __init__.pyc there (note the C in pyc)?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜