好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Python中关于模块查找的使用详解

这篇文章主要给大家介绍了python中模块查找的原理与方式,文中通过示例代码介绍的非常详细,对大家的学习或工作具有一定的参考学习价值,需要的朋友们下面跟着小编来一起学习学习吧。

#test.py
import os
import sys
print sys.path[0]
# execute
python test.py
python /Users/x/workspace/blog-code/p2016_05_28_python_path_find/test.py 
#ls
├── os.py
├── test2.py
├── redis.py
#test2.py
import os
from redis import Redis
#execute test2.py
Traceback (most recent call last):
 File "/Users/x/workspace/blog-code/p2016_05_28_python_path_find/test2.py", line 1, in <module>
 from redis import Redis
ImportError: cannot import name Redis 
>>> import os.path
>>> import sys
>>> os.path.abspath(sys.path[0])
'/Users/x/workspace/blog-code'
>>> 
#test3.py
print __file__
#相对路径执行
python test3.py
test3.py
#绝对路径执行
python /Users/x/workspace/blog-code/p2016_05_28_python_path_find/test3.py
/Users/x/workspace/blog-code/p2016_05_28_python_path_find/test3.py 
>>> __file__
Traceback (most recent call last):
 File "<input>", line 1, in <module>
NameError: name '__file__' is not defined 
#test.py
import sys
print __file__
print sys.argv[0] 
#test.py
import sys
print __file__
print sys.argv[0]
#test2.py
import test
#execute test2.py
/Users/x/workspace/blog-code/p2016_05_28_python_path_find/child/test.py #__file__
test2.py #sys.argv[0] 
>>> import sys
>>> sys.modules['tornado']
Traceback (most recent call last):
 File "<input>", line 1, in <module>
KeyError: 'tornado'
>>> import tornado
>>> sys.modules['tornado']
<module 'tornado' from '/Users/x/python_dev/lib/python2.7/site-packages/tornado/__init__.pyc'> 
>>> sys.modules['os']
<module 'os' from '/Users/x/python_dev/lib/python2.7/os.pyc'>
>>> 
>>> import os
>>> os.path.realpath(sys.modules['os'].__file__)
'/Users/x/python_dev/lib/python2.7/os.pyc'
>>> import tornado
>>> os.path.realpath(sys.modules['tornado'].__file__)
'/Users/x/python_dev/lib/python2.7/site-packages/tornado/__init__.pyc' 
def get_module_dir(name):
 path = getattr(sys.modules[name], '__file__', None)
 if not path
 raise AttributeError('module %s has not attribute __file__'%name)
 return os.path.dirname(os.path.abspath(path)) 

summary

总的来说,Python 是通过查找 sys.path 来决定包的导入,并且系统包优先级>同目录> sys.path ,Python 中的特有属性 __file__ 以及 sys.argv[0] , sys.modules 都能帮助我们理解包的查找和导入概念,只要能正确理解 sys.path 的作用和行为,理解包的查找就不是难题了。

总结

以上就是Python中关于模块查找的使用详解的详细内容,更多请关注Gxl网其它相关文章!

查看更多关于Python中关于模块查找的使用详解的详细内容...

  阅读:55次