Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

python - 即使使用__init__.py,也如何解决“尝试以非软件包方式进行相对导入”(How to fix “Attempted relative import in non-package” even with __init__.py)

I'm trying to follow PEP 328 , with the following directory structure:

(我正在尝试使用以下目录结构来遵循PEP 328 :)

pkg/
  __init__.py
  components/
    core.py
    __init__.py
  tests/
    core_test.py
    __init__.py

In core_test.py I have the following import statement

(在core_test.py我有以下导入语句)

from ..components.core import GameLoopEvents

However, when I run, I get the following error:

(但是,当我运行时,出现以下错误:)

tests$ python core_test.py 
Traceback (most recent call last):
  File "core_test.py", line 3, in <module>
    from ..components.core import GameLoopEvents
ValueError: Attempted relative import in non-package

Searching around I found " relative path not working even with __init__.py " and " Import a module from a relative path " but they didn't help.

(到处搜索时,我发现“ 即使使用__init__.py,相对路径也不起作用 ”和“ 从相对路径导入模块 ”,但它们没有帮助。)

Is there anything I'm missing here?

(我在这里想念什么吗?)

  ask by skytreader translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To elaborate on Ignacio Vazquez-Abrams's answer:

(详细阐述伊格纳西奥·巴斯克斯(Ignacio Vazquez-Abrams)的答案:)

The Python import mechanism works relative to the __name__ of the current file.

(Python导入机制相对于当前文件的__name__ 。)

When you execute a file directly, it doesn't have its usual name, but has "__main__" as its name instead.

(当您直接执行文件时,它没有通常的名称,而是使用"__main__"作为其名称。)

So relative imports don't work.

(因此,相对进口无效。)

You can, as Igancio suggested, execute it using the -m option.

(您可以按照Igancio的建议使用-m选项执行它。)

If you have a part of your package that is meant to be run as a script, you can also use the __package__ attribute to tell that file what name it's supposed to have in the package hierarchy.

(如果包的一部分要作为脚本运行,则还可以使用__package__属性告诉该文件在包层次结构中应具有的名称。)

See http://www.python.org/dev/peps/pep-0366/ for details.

(有关详细信息,请参见http://www.python.org/dev/peps/pep-0366/ 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...