상대 가져 오기-ModuleNotFoundError : x라는 모듈이 없습니다.
이것은 내가 정말로 앉아서 파이썬 3을 시도한 것은 처음이며 비참하게 실패하는 것 같습니다. 다음 두 파일이 있습니다.
- test.py
- config.py
config.py에는 몇 가지 변수와 함께 몇 가지 함수가 정의되어 있습니다. 나는 그것을 다음과 같이 제거했습니다.
그러나 다음과 같은 오류가 발생합니다.
ModuleNotFoundError: No module named 'config'
py3 규칙은 절대 가져 오기를 사용하는 것임을 알고 있습니다.
from . import config
그러나 이로 인해 다음 오류가 발생합니다.
ImportError: cannot import name 'config'
그래서 여기서 무엇을 해야할지 모르겠습니다 ... 어떤 도움이라도 대단히 감사합니다. :)
요약 : 모듈이 패키지의 일부가 아니기 때문에 실행 하는 파일에서 상대 가져 오기를 수행 할 수 없습니다 __main__
.
절대 수입 -사용 가능한 수입품sys.path
상대 가져 오기 -현재 모듈과 관련된 항목 가져 오기, 패키지의 일부 여야 함
두 변형을 똑같은 방식으로 실행하는 경우 둘 중 하나가 작동합니다. 어쨌든, 여기에 무슨 일이 일어나고 있는지 이해하는 데 도움이되는 예제가 있습니다 main.py
. 다음과 같은 전체 디렉토리 구조로 다른 파일을 추가해 보겠습니다 .
.
./main.py
./ryan/__init__.py
./ryan/config.py
./ryan/test.py
그리고 무슨 일이 일어나고 있는지 확인하기 위해 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
먼저 test.py를 실행 해 보겠습니다.
$ python ryan/test.py
__main__
Relative import failed
True
여기에서 "시험" 이다__main__
모듈과 패키지에 속하는 대해 아무것도 알지 못한다. 그러나 폴더가 sys.path에 추가 import config
되므로 작동 ryan
합니다.
대신 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.
Hope this helped.
P.S.: if you're sticking with Python 3 there is no more need in __init__.py
files.
I figured it out. Very frustrating, especially coming from python2.
You have to add a .
to the module, regardless of whether or not it is relative or absolute.
I created the directory setup as follows.
/main.py
--/lib
--/__init__.py
--/mody.py
--/modx.py
modx.py
def does_something():
return "I gave you this string."
mody.py
from modx import does_something
def loaded():
string = does_something()
print(string)
main.py
from lib import mody
mody.loaded()
when I execute main, this is what happens
$ python main.py
Traceback (most recent call last):
File "main.py", line 2, in <module>
from lib import mody
File "/mnt/c/Users/Austin/Dropbox/Source/Python/virtualenviron/mock/package/lib/mody.py", line 1, in <module>
from modx import does_something
ImportError: No module named 'modx'
I ran 2to3, and the core output was this
RefactoringTool: Refactored lib/mody.py
--- lib/mody.py (original)
+++ lib/mody.py (refactored)
@@ -1,4 +1,4 @@
-from modx import does_something
+from .modx import does_something
def loaded():
string = does_something()
RefactoringTool: Files that need to be modified:
RefactoringTool: lib/modx.py
RefactoringTool: lib/mody.py
I had to modify mody.py's import statement to fix it
try:
from modx import does_something
except ImportError:
from .modx import does_something
def loaded():
string = does_something()
print(string)
Then I ran main.py again and got the expected output
$ python main.py
I gave you this string.
Lastly, just to clean it up and make it portable between 2 and 3.
from __future__ import absolute_import
from .modx import does_something
Setting PYTHONPATH can also help with this problem.
Here is how it can be done on Windows
set PYTHONPATH=.
Tried your example
from . import config
got the following SystemError:
/usr/bin/python3.4 test.py
Traceback (most recent call last):
File "test.py", line 1, in
from . import config
SystemError: Parent module '' not loaded, cannot perform relative import
This will work for me:
import config
print('debug=%s'%config.debug)
>>>debug=True
Tested with Python:3.4.2 - PyCharm 2016.3.2
Beside this PyCharm offers you to Import this name.
You hav to click on config
and a help icon appears.
You can simply add following file to your tests directory, and then python will run it before the tests
__init__.py file
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
You have to append the module’s path to PYTHONPATH
:
export PYTHONPATH="${PYTHONPATH}:/path/to/your/module/"
This example works on Python 3.6.
I suggest going to Run -> Edit Configurations
in PyCharm, deleting any entries there, and trying to run the code through PyCharm again.
If that doesn't work, check your project interpreter (Settings -> Project Interpreter) and run configuration defaults (Run -> Edit Configurations...).
Declare correct sys.path list before you call module:
import os, sys
#'/home/user/example/parent/child'
current_path = os.path.abspath('.')
#'/home/user/example/parent'
parent_path = os.path.dirname(current_path)
sys.path.append(parent_path)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'child.settings')
As was stated in the comments to the original post, this seemed to be an issue with the python interpreter I was using for whatever reason, and not something wrong with the python scripts. I switched over from the WinPython bundle to the official python 3.6 from python.org and it worked just fine. thanks for the help everyone :)
참고URL : https://stackoverflow.com/questions/43728431/relative-imports-modulenotfounderror-no-module-named-x
'Programming' 카테고리의 다른 글
Mongo : 특정 필드가없는 항목 찾기 (0) | 2020.08.11 |
---|---|
Postgres : 고유하지만 단 하나의 열 (0) | 2020.08.11 |
내 Javascript 파일의 캐싱을 방지하는 방법은 무엇입니까? (0) | 2020.08.11 |
django 2.0의 urls.py에서 path () 또는 url ()을 사용하는 것이 더 낫습니까? (0) | 2020.08.11 |
JSX에서 "내보내기 기본값"은 무엇을합니까? (0) | 2020.08.11 |