从python中的不同目录导入 [英] Import from different directories in python
问题描述
这是我的文件夹结构:
src/
__init__py
Lowlevel/
__init__.py
ModuleToCheck.Py
Test/
__init__.py
ModuleToCheck_test.py
( __ init __。py
是空文件)
现在我要导入 ModuleToCheck.py
in ModuleToCheck_test.py
Now I want to import ModuleToCheck.py
in ModuleToCheck_test.py
我是怎么回事我能够做到这一点而不添加任何东西到 sys.path
?
How am I able to do this without appending anything to sys.path
?
更新:
来自..Lowlevel import ModuleToCheck
导致:
src$ python Test/ModuleToCheck_test.py
Traceback (most recent call last):
File "Test/ModuleToCheck_test.py", line 6, in <module>
from ..Lowlevel import ModuleToCheck
ValueError: Attempted relative import in non-package
推荐答案
以下内容来自 http ://docs.python.org/tutorial/modules.html#intra-package-references
请注意,两者都是明确的隐式
相对导入基于当前模块的名称
。由于主模块的名称
总是__ main __
,因此模块打算使用
作为Python $的主要模块b $ b应用程序应始终使用绝对
导入。
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.
您正在运行模块 ModuleToCheck_test .py
作为主要模块,因此是例外。
You're running your module ModuleToCheck_test.py
as the main module, hence the exception.
一种解决方案是创建 test.py 您的
src
目录中的code>模块包含以下内容:
One solution is to create a test.py
module in your src
directory containing the following:
import Test.ModuleToCheck_test
然后,您可以使用 python test运行该模块。 py
这篇关于从python中的不同目录导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!