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. 文件结构:
2. From the surround module for example, you can use:
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
相关文章推荐
- Python:Relative import 相对路径 ValueError: Attempted relative import in non-package
- python引入pytesseract报错:ValueError: Attempted relative import in non-package
- python:Attempted relative import in non-package
- Python中的Attempted relative import in non-package问题
- 解决python相对导入出现错误:Attempted relative import beyond toplevel package
- Attempted relative import in non-package
- ValueError: Attempted relative import in non-package
- [译][python]ImportError:attempted relative import with no known parent package
- ImportError: attempted relative import with no known parent package
- Python解析json之ValueError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
- python项目中不同文件夹py源文件之间如何相互调用--Python import中相对路径的问题
- python 使用相对路径import 模块的方法
- Python Import机制-模块搜索路径(sys.path)、嵌套Import、package Import
- python的package import 以及相对导入和绝对导入
- python的package import 以及相对导入和绝对导入
- 步步学习Python 编程error篇:import package error:Import error: No module named mayavi
- python import 相对路径
- Python import中相对路径的问题
- python调用py方法,报错【ValueError: no such test method in <class 'mytestcase.MyTestCase'>: runTest】
- Python Import机制备忘-模块搜索路径(sys.path)、嵌套Import、package Import