在import
模块的时候,python是经过系统路径找到这些模块的,咱们能够将这些路径打印出来:python
>>> pprint.pprint(sys.path) ['', '/Library/Python/2.7/site-packages/pip-1.4.1-py2.7.egg', '/Library/Python/2.7/site-packages/python_recsys-0.2-py2.7.egg', '/Users/zhanglixin/opensource/ipython', '/Library/Python/2.7/site-packages/pexpect-3.0-py2.7.egg', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC', '/Library/Python/2.7/site-packages']
那么,咱们放进这些路径里的模块或包,就能够不需指定路径,直接使用import
导入了。特别的,/Library/Python/2.7/site-packages
,咱们经常使用的应该放在这里。app
引入某一特定路径下的模块python2.7
sys.path.append(yourmodulepath)
将一个路径加入到python系统路径下,避免每次经过代码指定路径code
export PYTHONPATH=$PYTHONPATH:yourmodulepath
,/Library/Python/2.7/site-packages
目录下好的建议ip
if __name__ == '__main__'
,保证你写包既能够import又能够独立运行,用于test。reload
来强制运行模块,但不提倡。为了组织好模块,将多个模块分为一个包。包是python模块文件所在的目录,且该目录下必须存在__init__.py
文件。常见的包结构以下:it
package_a ├── __init__.py ├── module_a1.py └── module_a2.py package_b ├── __init__.py ├── module_b1.py └── module_b2.py main.py
main.py
想要引用packagea
中的模块module
a1
,能够使用:from package_a import module_a1 import package_a.module_a1
packagea
中的module
a1
须要引用packageb
,那么默认状况下,python是找不到package
b
。咱们能够使用sys.path.append('../')
,能够在packagea
中的__init__.py
添加这句话,而后该包下得全部module都添加* import __init
_
便可。