python 搜索路径及设置模块

模块搜索路径

当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

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值