python - 从同一文件导入引发 ImportError

标签 python python-3.x python-import importerror

很抱歉提问,但我找不到答案。 我有这棵树:

Dogs&Sheeps
    simulation.py
    stuff
        main.py
        values.py

simulation.py 中的代码开始:

import pygame
import sys

from stuff import main
from stuff import values

main.py 中的代码开始:

from random import randint
from time import sleep
import queue
import pygame
import sys

import values

如果我启动 simulation.py 会出现此错误:

    Traceback (most recent call last):
  File "...\simulation.py", line 5, in <module>
    from stuff import main
  File "...\stuff\main.py", line 7, in <module>
    import values
ImportError: No module named 'values'

我想我想做什么很明显,但无论如何。在文件 main.py 中,我想导入位于同一文件夹中的文件 values.py

最佳答案

在 Python 3.x 中,来自 documentation -

When packages are structured into subpackages (as with the sound package in the example), you can use absolute imports to refer to submodules of siblings packages. For example, if the module sound.filters.vocoder needs to use the echo module in the sound.effects package, it can use from sound.effects import echo .

以同样的方式,你需要使用绝对包名称,而不是相对名称,所以在你的 main.py 做 -

from stuff import values 

关于python - 从同一文件导入引发 ImportError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31867496/

相关文章:

python - 在 Flask shell 中运行 Flask 应用程序时出现 AttributeError

python - 使用 Apache 配置 Roundup

python - python3 中的 pkgutil.walk_packages 需要 __init__.py 吗?

python import 只能以一种格式工作

python - 如何重新定义我在 python 中导入的函数使用的函数?

python - 从同级目录导入 (python 3)

python - 如果文件在 Python 中不存在,则以原子方式创建文件

python - 为什么 pandas 的应用比 dataframe 合并慢得多

python - 在 macOS (Sierra) 上安装 PyQt5(包括 Qt Designer)

python - 在数据帧中查找第一个匹配对并标记两者