python第三方模块的导入

模块搜索路径

当我们尝试加载一个模块时,Python会在指定的路径下搜索对应的.py文件,如果找不到,就会报错:

>>> import module1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named module1

默认情况下,Python解释器会搜索当前目录、所有已安装的内置模块和第三方模块,搜索路径存放在sys模块的path变量中:

>>> import sys
>>> sys.path
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old']

如果我们要添加自己的搜索目录,有两种方法:

一是直接修改sys.path,添加要搜索的目录:

>>> import sys
>>> sys.path.append('/usr/share/doc/python-wxtools')

二是修改PYTHONPATH,只添加自己的搜索路径即可

1.  在/etc/profile  或者 ~/.bashrc 中输出环境变量

export PYTHONPATH=$PYTHONPATH:模块路径

 2.  source /etc/profile

 
 
 
原文地址:https://www.cnblogs.com/i1991/p/6867905.html