Original http://wuyanzan60688.blog.163.com/blog/static/1277761632011102113211189/
A
|----- __init__.py
|----- a.py
|---------B
|--------- __init__.py
|---------b.py
|---------C
|--------- __init__.py
|--------c.py
As shown in the structure tree, B and C belong to A's subdirectories, but B and C are parallel. . .
The codes of b.py and c.py are as follows:
b.py:
def b_hello():
print "B_HELLO"
c.py:
def c_hello():
print "C_HELLO"
If a.py in A wants to call py in B or C, it can be called as follows (take B as an example)
from B import b
b.b_hello()
Operation result: B_HELLO
But what if py in B or C calls B or C?
At this time, if we still use the call as mentioned above, an error will be reported (here is b.py calling c.py)
>>>
Traceback (most recent call last):
File "E:\testnow\A\B\b.py", line 1, in <module>
from C import c
ImportError: No module named C
So, this method does not work, how to do it, as follows
import sys
sys.path.append('E:\\testnow\\A\\C')
import c
def b_hello():
print "B_HELLO"
c.c_hello()
用这种方法,输出结果是:C_HELLO
也即刚才上面的“from 文件夹 import 模块名”只适用于父目录调用子目录的情况。。。而第二种方法则对所有的情况都适用,包括两个模块甚至都不在一个盘的情况。。。这里需要注意的一点是:sys.path添加目录时注意是在windows还是在linux下,windows下需要‘\\’否则会出错。。。。。。。(我在这点上走了很久的弯路。。。)