您的位置:首页 > 编程语言 > Python开发

Python:Relative import 相对路径 ValueError: Attempted relative import in non-package

2012-03-09 19:35 483 查看
包含相对路径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.

相对路径的具体规则可以对照如下:

1. 文件结构:

sound/                          Top-level package
__init__.py               Initialize the sound package
formats/                  Subpackage for file format conversions
__init__.py
wavread.py
wavwrite.py
aiffread.py
aiffwrite.py
auread.py
auwrite.py
...
effects/                  Subpackage for sound effects
__init__.py
echo.py
surround.py
reverse.py
...
filters/                  Subpackage for filters
__init__.py
equalizer.py
vocoder.py
karaoke.py
...


2. From the surround module for example, you can use:

from . import echo
from .. import formats
from ..filters import equalizer
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: