python导入模块路径优先级问题

优先级只需要

import sys

print sys.path

就可以看到,优先级是按照从前向后排列的

' '代表脚本当前位置,import优先级是最高的,其次是方法1设置的PYTHONPATH

>>> import sys
>>> print sys.path
['', '/home/www/oadata.xesv5.com', '/usr/local/lib/python27.zip', '/usr/local/lib/python2.7', '/usr/local/lib/python2.7/plat-linux2', '/usr/local/lib/python2.7/lib-tk', '/usr/local/lib/python2.7/lib-old', '/usr/local/lib/python2.7/lib-dynload', '/home/dev/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/site-packages', '/home/dev/data/common_search', '/usr/local/lib/python2.7/site-packages/setuptools-33.1.1-py2.7.egg', '/usr/local/lib/python2.7/site-packages/pip-19.0.1-py2.7.egg']

注意在不同的优先级如果有相同的导入模块,那么只有最高优先级的模块起作用!

方法1 这个优先级是最高的

vim /etc/profile
export PYTHONPATH=/home/www/oadata.xesv5.com
source /etc/profile #每个打开的shell界面都要source起作用

方法2

import sys
sys.path.insert(0,'/home/dev/data')
reload(sys) #加不加都起作用
>>> import sys
>>> print sys.path
['', '/home/www/oadata.xesv5.com', '/usr/local/lib/python27.zip', '/usr/local/lib/python2.7', '/usr/local/lib/python2.7/plat-linux2', '/usr/local/lib/python2.7/lib-tk', '/usr/local/lib/python2.7/lib-old', '/usr/local/lib/python2.7/lib-dynload', '/home/dev/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/site-packages', '/home/dev/data/common_search', '/usr/local/lib/python2.7/site-packages/setuptools-33.1.1-py2.7.egg', '/usr/local/lib/python2.7/site-packages/pip-19.0.1-py2.7.egg']
>>> sys.path.insert(0,'/home/dev/data')
>>> print sys.path
['/home/dev/data', '', '/home/www/oadata.xesv5.com', '/usr/local/lib/python27.zip', '/usr/local/lib/python2.7', '/usr/local/lib/python2.7/plat-linux2', '/usr/local/lib/python2.7/lib-tk', '/usr/local/lib/python2.7/lib-old', '/usr/local/lib/python2.7/lib-dynload', '/home/dev/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/site-packages', '/home/dev/data/common_search', '/usr/local/lib/python2.7/site-packages/setuptools-33.1.1-py2.7.egg', '/usr/local/lib/python2.7/site-packages/pip-19.0.1-py2.7.egg']

可以看到'/home/dev/data' 排在了当前位置 ‘ ’的前面,但是只在当前运行脚本起作用

方法3

import sys
sys.path.append('/home/dev/data2')

append 是按照数组顺序添加在最后面,优先级最低

 

你可能感兴趣的:(python)