简体   繁体   English

Python 3 - ImportError:无法导入名称

[英]Python 3 - ImportError: cannot import name

I have a folder:我有一个文件夹:

python_scripts/test_import/
|-- __init__.py
|-- m1.py
`-- m2.py

Content of m1.py : m1.py的内容:

a=3

Content of m2.py : m2.py的内容:

from . import m1

print(m1.a)

When I try to execute m2.py , I get the following error:当我尝试执行m2.py时,出现以下错误:

# python3 python_scripts/test_import/m2.py
Traceback (most recent call last):
  File "python_scripts/test_import/m2.py", line 1, in <module>
    from . import m1
ImportError: cannot import name 'm1'

But if I change import in m2.py to this:但是,如果我将m2.py中的导入更改为:

import m1

print(m1.a)

then I see no errors and result of execution is expected:然后我看不到任何错误,并且执行结果是预期的:

3

Question: Why relative import with dot doesn't work here?问题:为什么用点的相对导入在这里不起作用?

Error: can't import name m1 Relative import uses the name attribute of the imported file to determine the location of the file in the entire package structure, but when the python script is run directly, the name of the module is set to main instead of the original name of the module.错误:can't import name m1 相对导入使用导入文件的name属性来确定文件在整个package结构中的位置,但是直接运行python脚本时,模块的名称改为main模块的原始名称。 In this way, the relative path cannot be recognized.这样就无法识别相对路径。 So for this you can't just directly using that, your main.py need to be on the top files因此,为此您不能直接使用它,您的 main.py 需要位于顶部文件中

python_scripts/     
  |-- main.py :from test_import.m import m2
    /test_import/
      _init_.py
      /m/
        |-- __init__.py
        |-- m1.py
        |-- m2.py

Or if you insist to do so, you have to change into from.m1 import *或者如果你坚持这样做,你必须更改为 from.m1 import *

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM