python import相对路径

包含相对路径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 plain copy
  1. sound/                          Top-level package  
  2.       __init__.py               Initialize the sound package  
  3.       formats/                  Subpackage for file format conversions  
  4.               __init__.py  
  5.               wavread.py  
  6.               wavwrite.py  
  7.               aiffread.py  
  8.               aiffwrite.py  
  9.               auread.py  
  10.               auwrite.py  
  11.               ...  
  12.       effects/                  Subpackage for sound effects  
  13.               __init__.py  
  14.               echo.py  
  15.               surround.py  
  16.               reverse.py  
  17.               ...  
  18.       filters/                  Subpackage for filters  
  19.               __init__.py  
  20.               equalizer.py  
  21.               vocoder.py  
  22.               karaoke.py  
  23.               ...  


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

[plain]  view plain copy
  1. from . import echo  
  2. from .. import formats  
  3. from ..filters import equalizer  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值