importlib에서 import_module을 사용하여 모듈을 가져 오려고합니다. 그렇게하면 내 모듈에서 참조하는 파일을 찾을 수 없습니다. Python 쉘 (main.py를 사용하지 않음)에서 모듈을 정상적으로 가져 오면 예상대로 작동합니다. 또한, sys.path에 MyModule.py의 경로를 추가하면 작동하지만, 내가 이해할 수는 없지만 (아래 코드에서 주석 처리했습니다.)import_module로로드 할 때 모듈에서 파이썬 파일 참조하기
모듈이 import_module에 의해로드 될 때 참조 된 파일을로드하려면 어떻게합니까?
나는 다음과 같은 파일 구조를 hello.py
MyModule.py
#This is the solution that works but feels wrong
#import os, sys
#sys.path.append(os.path.dirname(__file__))
from hello import hello_world
class MyModule(object):
def __init__(self):
print("Init MyModule")
def module_hello(self):
hello_world()
내용의 main.py
from importlib import import_module
modulename = 'subfolders.folder1.MyModule'
print("Import module ", modulename)
module = import_module(modulename)
m_instance = module.MyModule()
m_instance.module_hello()
내용의
main.py
subfolders
folder1
__init__.py
MyModule.py
hello.py
내용이 나는이 프로그램을 실행할 때
def hello_world():
print("Hello World!")
내가 얻을 :
c:\git\PythonImportTest>python main.py
Import module subfolders.folder1.MyModule
Traceback (most recent call last):
File "main.py", line 5, in <module>
module = import_module(modulename)
File "C:\Miniconda3\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "c:\git\PythonImportTest\subfolders\folder1\MyModule.py", line 5, in <module>
from hello import hello_world
ImportError: No module named 'hello'