├── effects
│ ├── echo.py
│ ├── __init__.py
│ ├── reverse.py
│ ├── surround.py
├── filters
│ ├── equalizer.py
│ ├── __init__.py
│ ├── karaoke.py
│ ├── vocoder.py
├── formats
│ ├── aiffread.py
│ ├── aiffwrite.py
│ ├── auread.py
│ ├── auwrite.py
│ ├── __init__.py
│ ├── wavread.py
│ ├── wavwrite.py
├── __init__.py
└── sound.py
- import os
- print 'current file:'
- print os.path.realpath(__file__)
- print 'working dir:'
- print os.getcwd()
- from filters import equalizer
-
equalizer.fun()
- from sound.filters import equalizer
- equalizer.fun()
-
import os - print 'current file:'
- print os.path.realpath(__file__)
- print 'working dir:'
- print os.getcwd()
- from filters import *
-
print type(vocoder)
然后运行 python sound/sound.py, 得到以下的运行结果:songwei@songwei-ThinkPad-T410:~/WeiSONG/python/sound$ python sound.py
current file:
/home/songwei/WeiSONG/python/sound/sound.py
working dir:
/home/songwei/WeiSONG/python/sound
Traceback (most recent call last):
File "sound.py", line 9, in <module>
print type(vocoder)
NameError: name 'vocoder' is not defined
from .. import formats
from ..effects import surround
print 'current file:'
print os.path.realpath(__file__)
print 'working dir:'
print os.getcwd()
from filte rs import equalizer
ValueError: Attempted relative import beyond toplevel package
目录树
case2/
├── cat
│ ├── __init__.py
│ ├── cat.py
│ └── cat.pyc
├── dog
│ ├── __init__.py
│ └── dog.py
├── __init__.py
└── main.py
代码
# case2/cat/cat.py from .. import dog # case2/main.py import cat.cat
执行
# python case2/main.py
ValueError: Attempted relative import beyond toplevel package
错误原因
这里的 case2 是一个包,但当你直接执行 main.py 的时候,就没有把完整的 case2 当作一个包来处理了,可想而知,下层的 cat.py 自然找不到上层包了。即想要相对导入成功,必须让下层的被导入对象是上层包或上层包内的对象。
equalizer.fun()
current file:
/home/songwei/WeiSONG/python/sound/filters/equalizer.pyc
working dir:
/home/songwei/WeiSONG/python
in filters/equalizer.py
current file:
/home/songwei/WeiSONG/python/sound/filters/vocoder.pyc
working dir:
/home/songwei/WeiSONG/python
current file:
/home/songwei/WeiSONG/python/sound/effects/surround.pyc
working dir:
/home/songwei/WeiSONG/python
in equalizer
375



被折叠的 条评论
为什么被折叠?



