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
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
相关文章推荐
- Python import中相对路径的问题
- python项目中不同文件夹py源文件之间如何相互调用--Python import中相对路径的问题
- Python:Relative import 相对路径 ValueError: Attempted relative import in non-package
- Python import相对路径
- python 使用相对路径import 模块的方法
- python import 相对路径
- Python如何从相对路径下import
- Python:Relative import 相对路径 ValueError: Attempted relative import in non-package
- Python Import机制备忘-模块搜索路径(sys.path)、嵌套Import、package Import
- Python Import机制备忘-模块搜索路径(sys.path)、嵌套Import、package Import
- Python Import机制备忘-模块搜索路径(sys.path)、嵌套Import、package Import
- Python Import机制备忘-模块搜索路径(sys.path)、嵌套Import、package Import
- python import路径问题
- Python Import机制备忘-模块搜索路径(sys.path)、嵌套Import、package Import
- Python Import机制备忘-模块搜索路径(sys.path)、嵌套Import、package Import
- Robot Framework中Python加载相对路径DLL
- C++使用boost python import 其他路径的模块
- python import 路径设置
- from ....import导入其他路径的模块 分类: python基础学习 2013-10-11 15:13 315人阅读 评论(0) 收藏
- 调试用Python C API 写的程序问题还真多,关于import搜索路径的,复制过来,以防忘记