模块搜索路径
当import某个模块时,解释器首先搜索具有该名称的内置模块,
如果没有找到,将在变量 sys.path 给出的目录列表中搜索名为 模块名.py 的文件。
sys.path 包含了一下几个目录:
- 输入脚本的当前目录;
- PYTHONPATH环境变量;
- python安装时的系统目录;
>>> import sys
>>> sys.path
['', '/usr/lib64/python27.zip', '/usr/lib64/python2.7',
'/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk',
'/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload',
'/usr/lib64/python2.7/site-packages', '/usr/lib/python2.7/site-packages']
设置模块路径
在/root/ws目录下建一个hello.py文件
def test():
print('hello')
return
1、使用sys.path.append 临时动态添加模块的路径:
>>> sys.path.append('/root/ws')
>>> sys.path
['', '/usr/lib64/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7/site-packages', '/usr/lib/python2.7/site-packages', '/root/ws']
>>>
>>> import hello
>>> hello.test()
hello
2、修改PYTHONPATH环境变量:
vim ~/.bashrc
#添加
export PYTHONPATH=$PYTHONPATH:/root/ws
#生效
source ~/.bashrc
#python代码中引入hello模块
$ python
Python 2.7.5 (default, Sep 15 2016, 22:37:39)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/root', '/root/ws', '/usr/lib64/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7/site-packages', '/usr/lib/python2.7/site-packages']
>>> import hello
>>> hello.test()
hello
3、使用.pth文件:
在/usr/lib/python2.7/site-packages 下添加一个扩展名为 .pth 的配置文件(例如:test.pth),内容为要添加的路径:
/root/ws