티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Relative imports - ModuleNotFoundError: No module named x
Relative imports - ModuleNotFoundError: x라는 모듈이 없습니다.
문제 내용
This is the first time I've really sat down and tried python 3, and seem to be failing miserably. I have the following two files:
파이썬 3를 실제로 앉아서 시도해 본 것은 이번이 처음인데, 비참하게 실패하고 있는 것 같다. 나는 다음 두 개의 파일을 가지고 있다:
- test.py
- config.py
test.py config.py
config.py has a few functions defined in it as well as a few variables. I've stripped it down to the following:
config.py에는 몇 가지 변수뿐만 아니라 몇 가지 함수가 정의되어 있습니다. 나는 그것을 다음과 같이 축소했다.
config.py
config.py
debug = True
test.py
test.py
import config
print (config.debug)
I also have an __init__.py
나는 또한 __init_.py를 가지고 있다.
However, I'm getting the following error:
그러나 다음 오류가 발생합니다.
ModuleNotFoundError: No module named 'config'
I'm aware that the py3 convention is to use absolute imports:
나는 py3 협약이 절대 수입품을 사용하는 것으로 알고 있다.
from . import config
However, this leads to the following error:
그러나 이로 인해 다음 오류가 발생합니다.
ImportError: cannot import name 'config'
So I'm at a loss as to what to do here... Any help is greatly appreciated. :)
그래서 여기서 뭘 해야 할지 막막해요 어떤 도움이든 대단히 감사합니다. :)
높은 점수를 받은 Solution
TL;DR: You can't do relative imports from the file you execute since __main__
module is not a part of a package.
TL;DR: __main_ 모듈이 패키지의 일부가 아니므로 실행하는 파일에서 상대 가져오기를 수행할 수 없습니다.
Absolute imports - import something available on sys.path
절대 가져오기 - sys.path에서 사용할 수 있는 항목 가져오기
Relative imports - import something relative to the current module, must be a part of a package
상대 가져오기 - 현재 모듈과 관련된 항목을 가져오십시오. 패키지의 일부여야 합니다.
If you're running both variants in exactly the same way, one of them should work. Here is an example that should help you understand what's going on. Let's add another main.py
file with the overall directory structure like this:
두 변형을 정확히 동일한 방식으로 실행하는 경우 둘 중 하나가 작동해야 합니다. 다음은 무슨 일이 일어나고 있는지 이해하는 데 도움이 되는 예입니다. 다음과 같은 전체 디렉터리 구조를 가진 다른 main.py 파일을 추가해 봅시다.
.
./main.py
./ryan/__init__.py
./ryan/config.py
./ryan/test.py
And let's update test.py
to see what's going on:
test.py을 업데이트하여 상황을 확인해 보겠습니다.
# config.py
debug = True
# test.py
print(__name__)
try:
# Trying to find module in the parent package
from . import config
print(config.debug)
del config
except ImportError:
print('Relative import failed')
try:
# Trying to find module on sys.path
import config
print(config.debug)
except ModuleNotFoundError:
print('Absolute import failed')
# main.py
import ryan.test
Let's run test.py
first:
먼저 test.py을 실행해 보겠습니다.
$ python ryan/test.py
__main__
Relative import failed
True
Here "test" is the __main__
module and doesn't know anything about belonging to a package. However import config
should work, since the ryan
folder will be added to sys.path
.
여기서 "test"는 __main_ 모듈이며 패키지에 속하는 것에 대해 아무것도 알지 못합니다. 그러나 ryan 폴더가 sys.path에 추가되므로 import config가 작동합니다.
Let's run main.py
instead:
대신 main.py을 실행해 봅시다.
$ python main.py
ryan.test
True
Absolute import failed
And here test is inside of the "ryan" package and can perform relative imports. import config
fails since implicit relative imports are not allowed in Python 3.
그리고 여기서 테스트는 "ryan" 패키지 안에 있으며 상대적인 가져오기를 수행할 수 있습니다. Python 3에서는 암묵적인 상대 가져오기가 허용되지 않으므로 가져오기 구성이 실패합니다.
Hope this helped.
이게 도움이 됐길 바라요.
P.S.: If you're sticking with Python 3 there is no more need for __init__.py
files.
추신: Python 3을 고수한다면 __init_.py 파일이 더 이상 필요하지 않습니다.
가장 최근 달린 Solution
I am working in a Linux machine. I had the same issue when I run python my_module/__main__.py
.
나는 리눅스 머신에서 일하고 있다. python my_module/_main_.py를 실행할 때도 같은 문제가 발생했습니다.
The error is fixed, if you run the command export PYTHONPATH=.
before your run your script.
스크립트를 실행하기 전에 export PYTHONPATH=. 명령을 실행하면 오류가 수정됩니다.
export PYTHONPATH=.
python my_module/__main__.py
출처 : https://stackoverflow.com/questions/43728431/relative-imports-modulenotfounderror-no-module-named-x
'개발 > 파이썬' 카테고리의 다른 글
pip를 사용하여 libxml 설치 오류 (0) | 2022.11.26 |
---|---|
도커 "오류: 네트워크에 할당할 기본값 중 중복되지 않는 사용 가능한 IPv4 주소 풀을 찾을 수 없습니다." (0) | 2022.11.26 |
Python 3 ImportError: 'ConfigParser'라는 모듈이 없습니다. (0) | 2022.11.26 |
Mac OS에서 PIP를 사용하여 PIL을 설치하는 방법은 무엇입니까? (0) | 2022.11.26 |
pandas에서 열 집합 선택/제외 (0) | 2022.11.26 |