Python import中相对路径的问题

gunicorn起动此项目时。  

报错:   

File "/usr/local/python2.7/lib/python2.7/site-packages/gunicorn/workers/workertmp.py", line 12, in <module>
    PLATFORM = platform.system()
AttributeError: 'module' object has no attribute 'system'

   然后看源码,platform是python自带的包,没有问题。最后经人指点,发现项目工程目录中有一个包名是Platform,去掉platform目录,就没问题了。

   所以自己写的项目无论是包名还是py文件名,还是类或者方法名,千万别跟Python自带的重名!

6.1.2. The Module Search Path

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.pathsys.path is initialized from these locations:

  • the directory containing the input script (or the current directory).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • the installation-dependent default.

After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended. See section Standard Modules for more information.

当导入名为 spam 的模块时, 解释器会先在当前目录下查找名为 spam.py 的文件, 然后搜索环境变量 PYTHONPATH 记录的所有目录. 这个变量与 shell 变量 PATH 有相同的语法, 它是一些目录名的列表. 当没有设置 PYTHONPATH , 或者在前述各种路径中都没找到期望的文件时, 那么解释器会在pyhton 安裝时定义的默认目录中搜寻. 在 Unix 中, 通常是在/usr/local/lib/python .

实际上, 都是在变量 sys.path 定义的目录列表中搜索模块的, 该变量初始化包含了执行脚本的目录 (或者当前目录) 以及 PYTHONPATH 和与安装时相关的默认目录. 这使得 Python 程序猿在必要的时候,可以直接进行更改或替代相关路径来进行模块搜索.

注意, 因为搜索目录包含当前运行脚本的目录, 所以令脚本名不与某个标准模块重名很重要, 否则 Python 会尝试把这个脚本当成一个模块载入, 而重名系统模块已经被导入时. 这通常会抛出一个错误. 参看 标准模块 小节获取更多信息.

PS:还有一种方式避免上述的问题,就是在每个py文件上的首行引入以下一行

from __future__ import absolute_import

也是可以解决上述问题。

原文地址:https://www.cnblogs.com/liuyongjians/p/3292163.html