Last active
August 29, 2015 14:23
-
-
Save tawateer/7a1df1f516ebd62523ea to your computer and use it in GitHub Desktop.
python pkgutil.extend_path 的作用
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pkgutil import extend_path | |
import sys | |
print __name__ | |
print __path__ | |
__path__ = extend_path(__path__, __name__) | |
print __path__ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
test 是一个目录: | |
test | |
├── __init__.py | |
└── echo.py | |
extend_path 会扫描 sys.path 下面的每一个目录, 如果目录下存在 __name__ 这个子目录, | |
而且子目录下存在 __init__.py 文件, 那么就把子目录加入 __path__ ; | |
而且 它会扫描 sys.path 的目录下是否有 __name__.pkg 文件, 如果有会把里面的路径都加到 __path__(不做检查). | |
下面是测试: | |
>>> import test | |
test | |
['test'] | |
['test', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/test'] | |
>>> from test import echo | |
Hello, world | |
>>> from test import test_hmac | |
看测试结果, echo 是 当前 test 目录下的模块, 而 test_hmac 是 | |
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/test 目录下的, | |
所以它实现了一个 package extend 了系统中同名的 package, 使其可以通过同一个 package name | |
来 import. | |
再解释一下 __path__ 的作用, __path__ 在 __init__.py 生成, 代表此 package 内的搜索路径. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env python | |
print "Hello, world." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment