python是如何找到对应的package的?

我们在写python代码或者阅读别人的代码时,可能会碰到对应module无法找到的问题,这时如何解决呢?我们如果对python解释器如何查找对应的module有比较深刻的理解,那么我们就可以轻松解决相关问题。

https://leemendelowitz.github.io/blog/how-does-python-find-packages.html

sys.path

import sys
print('\n'.join(sys.path))
# 当前目录
D:\devenv\Code\intro_ds\knowhow
D:\devenv\Code\intro_ds
# anaconda
D:\Continuum\Anaconda3\python35.zip
D:\Continuum\Anaconda3\DLLs
D:\Continuum\Anaconda3\lib
D:\Continuum\Anaconda3
D:\Continuum\Anaconda3\lib\site-packages
D:\Continuum\Anaconda3\lib\site-packages\Sphinx-1.4.6-py3.5.egg
D:\Continuum\Anaconda3\lib\site-packages\win32
D:\Continuum\Anaconda3\lib\site-packages\win32\lib
D:\Continuum\Anaconda3\lib\site-packages\Pythonwin
D:\Continuum\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.5.egg

上面看到sys.path目录包含了当前脚本所在的目录以及对应安装site环境,那么问题来了: 

sys.path是如何被赋值的

从python的文档中https://docs.python.org/2/library/sys.html#sys.path看到:sys.path使用当前的工作目录,以及罗列在PYTHONPATH环境变量中的目录,再加上installation-dependent default paths(这是由site模块来控制的)

如果你的PYTHONPATH环境变量并没有设置,则sys.path将包含:当前工作目录+site模块执行的目录变更。当你启动python时,site模块自动被imported加载。

https://docs.python.org/2/library/site.html#module-site

操作sys.path

import sys, os

# This won't work - there is no hi module
import hi 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named hi

# Create a hi module in your home directory.
home_dir = os.path.expanduser("~")
my_module_file = os.path.join(home_dir, "hi.py")
with open(my_module_file, 'w') as f:
  f.write('print "hi"\n')
  f.write('a=10\n')

# Add the home directory to sys.path
sys.path.append(home_dir)

# Now this works, and prints hi!
import hi 
print hi.a

module的__file__属性

当你import一个module时,你可以通过查看__file__属性来找到该module具体存在于哪个目录中:

> import numpy
> numpy.__file__
'/usr/local/lib/python2.7/dist-packages/numpy/__init__.pyc'

注意,以上对于静态编译到解释器的内置module不适用,比如sys模块就没有__file__属性

imp模块

 

posted @ 2018-08-02 15:36  世有因果知因求果  阅读(2685)  评论(0编辑  收藏  举报