티스토리 뷰
Stack Overflow 에 자주 검색 또는 등록되는 문제들을 정리하고 있습니다. 가장 높은 점수를 받은 Solution과 가장 최근에 업데이트 된 Solution 을 각각 정리하였습니다.
How to fix "Attempted relative import in non-package" even with __init__.py
Attempted relative import in non-package 문제 수정
문제 내용
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?
제가 여기서 놓친 것이 있나요?
높은 점수를 받은 Solution
To elaborate on Ignacio Vazquez-Abrams's answer:
이그나시오 바스케스-에이브람스의 답변을 자세히 설명하자면:
The Python import mechanism works relative to the __name__
of the current file. When you execute a file directly, it doesn't have its usual name, but has "__main__"
as its name instead. So relative imports don't work.
Python 가져오기 메커니즘은 현재 파일의 __name_에 상대적으로 작동합니다. 파일을 직접 실행하면 일반적인 이름은 없지만 대신 "__main__"을 이름으로 사용합니다. 그래서 상대적인 수입은 효과가 없다.
You can, as Igancio suggested, execute it using the -m
option. 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.
Igancio가 제안한 대로 -m 옵션을 사용하여 실행할 수 있습니다. 패키지의 일부가 스크립트로 실행되는 경우 __package__ 특성을 사용하여 패키지 계층에 있는 파일의 이름을 지정할 수도 있습니다.
See http://www.python.org/dev/peps/pep-0366/ for details.
자세한 내용은 http://www.python.org/dev/peps/pep-0366/을 참조하십시오.
가장 최근 달린 Solution
As you have already marked everything as a module, there's no need to use the relative reference if you launch as python module.
이미 모든 것을 모듈로 표시했으므로 파이썬 모듈로 실행하면 상대 참조를 사용할 필요가 없습니다.
Instead of
대신
from ..components.core import GameLoopEvents
simply
단순히
from pkg.components.core import GameLoopEvents
When you run from the parent of pkg, use the following
pkg의 상위에서 실행할 때는 다음을 사용하십시오.
python -m pkg.tests.core_test
출처 : https://stackoverflow.com/questions/11536764/how-to-fix-attempted-relative-import-in-non-package-even-with-init-py
'개발 > 파이썬' 카테고리의 다른 글
"ImportError: Cannot import name X" 또는 "AttributeError" 를 어떻게 해결하나요? (0) | 2022.11.25 |
---|---|
다른 .py 파일에서 함수를 호출하려면 어떻게 해야 합니까? (0) | 2022.11.25 |
가져오기 오류: 이름이 지정된 모듈 요청이 없습니다. (0) | 2022.11.25 |
virtualenv에서 Python 3 사용 (0) | 2022.11.25 |
[구현] 주식 일별시세 크롤링하기 (6) | 2020.11.30 |