试图在顶级包之外进行相对导入?

2024-04-26 03:21:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目录结构如下:

game/
    graphics/
          __init__.py
          render.py
    sound/
         __init__.py
         echo.py
    __init__.py

我的render.pyfrom ..sound.echo import echo_test, 但每次我运行它都会显示Attempted relative imports beyond top-level package
我该怎么解决这个问题?在


Tags: frompytestimportecho目录gameinit
2条回答

我猜您正在尝试以下方法,或者类似的方法:python render.py

但这是治疗render.py作为脚本而不是包的组件。如果你写一个外部脚本 import render,然后测试render函数,导入应该可以正常工作。在

您可能想看看Hitchhiker's Guide to Python

你需要相对进口吗?在

你能用from game.sound.echo import echo_test吗?在

但是,由于您没有显示确切的stacktrace,错误可能来自echo.py。不过,尝试的“import beyond top-level package”是不言自明的。在

PEP 328可能值得一读

相关问题 更多 >