[英]Can't import module from subdirectory
On a high level the structure of my project looks like this. 在较高的层次上,我的项目结构如下所示。
dir/
moduleA/
__init__.py
file1.py
file2.py
main.py
file2.py contains some global variable that I am importing in file1.py file2.py包含一些我要在file1.py中导入的全局变量
# --- file2.py schema ---
SOME_GLOBAL_VARIABLE = 1
. 。
# --- file1.py schema ---
from moduleA.file2 import SOME_GLOBAL_VARIABLE
class MyClass():
def __init__(self):
self.some_attr = SOME_GLOBAL_VARIABLE
def run():
print(self.some_attr)
When I run main.py below,which creates an instance of MyClass, the code runs without errors. 当我在下面运行main.py(创建MyClass的实例)时,代码运行没有错误。
# --- main.py ---
from moduleA.file1 import MyClass
x = MyClass()
x.run()
However, when I open a open a Python console and execute the below to import MyClass from file1.py I get an import error that there is no module named moduleA. 但是,当我打开一个Python控制台并执行以下操作从file1.py导入MyClass时,出现导入错误,即没有名为moduleA的模块。
from moduleA.file1 import MyClass
# (... some traceback statements)
from moduleA.file2 import SOME_GLOBAL_VARIABLE
ModuleNotFoundError: No module named 'moduleA'
How is this possible when Python clearly finds moduleA/file1.py, otherwise it could not try to execute the line 当Python清楚地找到moduleA / file1.py时,这怎么可能,否则它将无法尝试执行该行
from moduleA.file2 import SOME_GLOBAL_VARIABLE
What seems strange to me is that it runs without errors when I run the main.py script. 在我看来,奇怪的是,当我运行main.py脚本时,它运行时没有错误。
I guess this is due to my lack in understanding how Python exactly imports modules, so any help is greatly appreciated. 我猜这是由于我缺乏对Python如何准确导入模块的了解,因此非常感谢您的帮助。 I tried adding the init .py file in moduleA but this did not resolve the issue. 我尝试在moduleA中添加init .py文件,但这不能解决问题。
In case this information is of relevance, the path some_path/dir is on my PYTHONPATH. 如果此信息相关,则路径some_path / dir在我的PYTHONPATH上。
This is caused because of the __package__
variable. 这是由于__package__
变量引起的。
To see it's value, add print(__package__)
in file1.py
before the import. 要查看其值,请在file1.py
之前在file1.py
添加print(__package__)
。
When running file1.py
directly, you can see that __package__
is None
. 直接运行file1.py
,您会看到__package__
是None
。
But on the other hand, when running main.py
, when importing file1.py
(and thus running it), __package__
's value (in file1.py
) is suddenly moduleA
, which is why python is able to import moduleA.file2
. 但是另一方面,在运行main.py
,在导入file1.py
(并因此运行它)时, __package__
的值(在file1.py
)突然是moduleA
,这就是python能够导入moduleA.file2
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.