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

python import相对路径

2014-08-28 08:07 337 查看
包含相对路径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. 文件结构:

[plain] view
plaincopy

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:

[plain] view
plaincopy

from . import echo

from .. import formats

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