我跟着Python 3 Modules tutorial,我无法获得绝对或相对的包内导入。
具体来说,我从教程中复制了项目结构。 sound
文件夹位于我的主目录/home/user/
中。所有项目文件(filters/vocoder.py
和effects/surround.py
除外)均为空,并且已使用touch
生成。
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
根据指示filters/vocoder.py
包含:
from sound.effects import echo
执行此文件时,会导致导入错误:
user@pc:~/sound$ python filters/vocoder.py
Traceback (most recent call last):
File "filters/vocoder.py", line 1, in <module>
from sound.effects import echo
ImportError: No module named 'sound'
user@pc:~/sound$ cd filters/
user@pc:~/sound/filters$ python vocoder.py
Traceback (most recent call last):
File "vocoder.py", line 1, in <module>
from sound.effects import echo
ImportError: No module named 'sound'
同样,我分别在effects/surround.py
中执行了以下每行代码(我注释了#
行并重新运行脚本):
from . import echo
from .. import formats
from ..filters import equalizer
执行时会导致:
user@pc:~/sound$ python effects/surround.py
Traceback (most recent call last):
File "effects/surround.py", line 1, in <module>
from . import echo
SystemError: Parent module '' not loaded, cannot perform relative import
user@pc:~/sound$ cd effects/
user@pc:~/sound/effects$ python surround.py
Traceback (most recent call last):
File "surround.py", line 1, in <module>
from . import echo
SystemError: Parent module '' not loaded, cannot perform relative import
我做错了什么,为什么我的包裹中无法获得绝对和相对的进口?
下面是一个应该有助于复制项目的脚本:
mkdir ~/sound
touch ~/sound/__init__.py
mkdir ~/sound/formats
touch ~/sound/formats/__init__.py
touch ~/sound/folder/wavread.py
touch ~/sound/folder/wavwrite.py
touch ~/sound/folder/aiffread.py
touch ~/sound/folder/aiffwrite.py
touch ~/sound/folder/auread.py
touch ~/sound/folder/auwrite.py
mkdir ~/sound/effects
touch ~/sound/effects/__init__.py
touch ~/sound/folder/echo.py
touch ~/sound/folder/surround.py
touch ~/sound/folder/reverse.py
mkdir ~/sound/filters
touch ~/sound/filters/__init__.py
touch ~/sound/folder/equalizer.py
touch ~/sound/folder/vocoder.py
touch ~/sound/folder/karaoke.py
echo "from sound.effects import echo" >> ~/sound/filters/vocoder.py
echo "from . import echo" >> ~/sound/effects/surround.py
echo "from .. import formats" >> ~/sound/effects/surround.py
echo "from ..filters import equalizer" >> ~/sound/effects/surround.py
答案 0 :(得分:0)
我只是在看教程。我不认为from sound.effects import echo
应该按照filters/vocoders.py
的原样运作。本教程中的内容是:
包的用户可以从包中导入单个模块, 例如:
import sound.effects.echo
这就好像用户可以从当前目录引用sound
目录一样。就像一些评论所说的那样,为了做到这一点,用户需要与sound
位于同一目录中,或者将sound
目录添加到PATH
变量中。像这样:
import sys
sys.path.append( <path to sound> )
from sound.effects import echo
另请参阅:Import a module from a relative path
在教程的下方,他们会触及您要执行的操作,即intra-package references。您可以使用此技术而不将sound
添加到PATH
:
例如,从您的filters/vocoders.py
模块中,这应该可以导入echo
:
from ..effects import echo