首页 > 技术文章 > python绝对与相对引用问题(比较杂乱,懒得整理)

fuzzier 2016-11-30 10:07 原文

持续更新中,直到找到最好的方法

1 在stackoverflows摘抄

  • If the import module in the same dir, use e.g: from . import core
  • If the import module in the top dir, use e.g: from .. import core
  • If the import module in the other subdir, use e.g: from ..other import core

 

2 ValueError: Attempted relative import in non-package

包含相对路径import 的python脚本不能直接运行,只能作为module被引用。原因正如手册中描述的,所谓相对路径其实就是相对于当前module的路径,但如果直接执行脚本,这个module的name就是“__main__”, 而不是module原来的name, 这样相对路径也就不是原来的相对路径了,导入就会失败,出现错误“ValueError: Attempted relative import in non-package”

Note that both explicit and implicit relative imports are based on the name of the current module. Since the name of the main module is always"__main__", modules intended for use as the main module of a Python application should always use absolute imports.

在使用相对引用的文件中,不能有__main__方法,只执行作为一个module进行引用,而不是直接执行脚本。

 

3 利用路径引用其他目录下的文件

首先图中的目录结构

我在auth下的view.py文件上工作,但我需要app/aap.py中的变量db

而我想用下面这个方式引入发现不成功

方式一

from ..app import db

也查阅相关资料发现自己太愚并不能理解,所以另寻方法

 中间插一句

sys.path.append('你的模块的名称')。

sys.path.insert(0,'模块的名称')

方式二

import os
import sys
out = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(out)
import app
print app.db

测试之后发现成功(yeh)其中这两个dirname就相当于返回到app/目录下,然后又在环境路径下添加了app/所以可以导入app.py,我偷懒直接导入需要的app.db

方式三

import sys
sys.path.insert(0, '..')
#此时路径已经在app文件下了
import app
print app.db

 

4 命令行运行

python -m 目录.文件名

该方式是把模块当作脚本来启动(注意:但是__name__的值为'main' )

相当于在sys.path中加入了当前路径

 

5 把整个项目当做workspace

目前为止最好的办法

 

 然后就可以进行绝对路径引用或者相对路径引用了。

推荐阅读