当在py代码中import所依赖的模块时, python是从哪里找到这些模块呢,即模块的搜索路径是啥?
默认情况下,Python解释器会搜索当前目录、所有已安装的内置模块和第三方模块,搜索路径存放在sys
模块的path
变量中:
>>> import sys
>>> sys.path
['', 'C:\\Windows\\system32\\python27.zip', 'd:\\Program Files\\python27\\DLLs',
'd:\\Program Files\\python27\\lib', 'd:\\Program Files\\python27\\lib\\plat-win
', 'd:\\Program Files\\python27\\lib\\lib-tk', 'd:\\Program Files\\python27', 'd
:\\Program Files\\python27\\lib\\site-packages']
>>>
如果想要添加自定义路径,有两种办法:
一种是在运行时直接给sys.path添加路径,这种方法在当前脚本运行结束后,
自定义添加的路径即失效。
1 import sys
2
3 sys.path.append("../../ias_common")
第二种是将自定义路径添加到环境变量“PYTHONPATH”中,这种方法永久有效。