code

SystemError : 상위 모듈 ''이로드되지 않았습니다. 상대 가져 오기를 수행 할 수 없습니다.

codestyles 2020. 9. 6. 10:03
반응형

SystemError : 상위 모듈 ''이로드되지 않았습니다. 상대 가져 오기를 수행 할 수 없습니다.


이 질문에 이미 답변이 있습니다.

다음 디렉터리가 있습니다.

myProgram
└── app
    ├── __init__.py
    ├── main.py 
    └── mymodule.py

mymodule.py :

class myclass(object):

def __init__(self):
    pass

def myfunc(self):
    print("Hello!")

main.py :

from .mymodule import myclass

print("Test")
testclass = myclass()
testclass.myfunc()

하지만 실행하면 다음 오류가 발생합니다.

Traceback (most recent call last):
  File "D:/Users/Myname/Documents/PycharmProjects/myProgram/app/main.py", line 1, in <module>
    from .mymodule import myclass
SystemError: Parent module '' not loaded, cannot perform relative import

이것은 작동합니다 :

from mymodule import myclass

그러나 이것을 입력 할 때 자동 완성이되지 않고 "unresolved reference : mymodule"및 "unresolved reference : myclass"라는 메시지가 나타납니다. 작업중인 다른 프로젝트에서 "ImportError : No module named 'mymodule'."오류가 발생합니다.

어떡해?


나는 같은 문제가 있었고 상대 가져 오기 대신 절대 가져 오기를 사용하여 해결했습니다.

예를 들어 귀하의 경우 다음과 같이 작성합니다.

from app.mymodule import myclass

문서 에서 볼 수 있습니다 .

상대적 가져 오기는 현재 모듈의 이름을 기반으로합니다. 주 모듈의 이름은 항상 " __main__"이므로 Python 애플리케이션의 주 모듈로 사용하려는 모듈은 항상 절대 가져 오기를 사용해야합니다.


일반적으로이 해결 방법을 사용합니다.

try:
    from .mymodule import myclass
except Exception: #ImportError
    from mymodule import myclass

즉, IDE가 올바른 코드 위치를 선택해야하며 파이썬 인터프리터가 코드를 실행합니다.


main.py아래에서 실행하면 다음 app과 같이 가져옵니다.

from mymodule import myclass

main.py다른 폴더 를 호출 하려면 다음을 사용하십시오.

from .mymodule import myclass

예를 들면 :

├── app
│   ├── __init__.py
│   ├── main.py
│   ├── mymodule.py
├── __init__.py
└── run.py

main.py

from .mymodule import myclass

run.py

from app import main
print(main.myclass)

그래서 당신의 주된 질문은 전화하는 방법이라고 생각합니다 app.main.


If you go one level up in running the script in the command line of your bash shell, the issue will be resolved. To do this, use cd .. command to change the working directory in which your script will be running. The result should look like this:

[username@localhost myProgram]$

rather than this:

[username@localhost app]$

Once you are there, instead of running the script in the following format:

python3 mymodule.py

Change it to this:

python3 app/mymodule.py

This process can be repeated once again one level up depending on the structure of your Tree diagram. Please also include the compilation command line that is giving you that mentioned error message.

참고URL : https://stackoverflow.com/questions/33837717/systemerror-parent-module-not-loaded-cannot-perform-relative-import

반응형