[英]Python import package with and without it's namespace
I have a package called sound
with a directory structure like so: 我有一个名为sound
的软件包,其目录结构如下:
sound/
|-- __init__.py
|-- interpreter.py
|-- blast.py
Before I had the package, interpreter.py
would import blast.py
with the command import blast
. 在获得软件包之前, interpreter.py
将使用命令import blast
导入blast.py
。 Now with the package I have to say import sound.blast as blast
. 现在,对于该软件包,我不得不说import sound.blast as blast
。
While I don't mind this, I'd like to be able to both import the sound
package outside of it's directory with that statement, but also to run interpreter.py
directly. 尽管我对此不介意,但我希望既可以使用该语句将sound
包导入其目录之外,也可以直接运行interpreter.py
。 But if I run interpreter.py
directly, I get an import error saying that sound
doesn't exist. 但是,如果我直接运行interpreter.py
,则会收到导入错误,提示该sound
不存在。
My current solution is something like this: 我当前的解决方案是这样的:
try:
import sound.blast
except ImportError:
import blast
But this feels ugly. 但这感觉很难看。 Is there a better solution for this? 有更好的解决方案吗?
Another work around would be. 另一个解决方法是。
Replace the "try import" statement by the following lines into the interpreter.py file. 将以下行中的“ try import”语句替换为interpreter.py文件。
import sys
sys.path.append("..")
import sound.blast
Hence the parent directory will also be included in the path, then importing sound.blast within the sound directory wouldn't be a problem any more. 因此,父目录也将包含在路径中,然后在声音目录中导入sound.blast不再是问题。
Hope it helps 希望能帮助到你
The sys.path.append("..")
method actually didn't work properly for more complicated namespaces in my program. 对于我程序中更复杂的名称空间, sys.path.append("..")
方法实际上无法正常工作。 The best way I solved it was: 我解决它的最好方法是:
if __package__ == 'sound':
import sound.blast
else:
import blast
Then more complicated namespaces worked, such as sound.blast.driver.specification
然后可以使用更复杂的名称空间,例如sound.blast.driver.specification
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.