Python如何导入自定义的类
目录结构
project/
├── ultralytics/ # Ultralytics library
│ ├── utils/
│ │ ├── __init__.py
│ │ ├── settings.py
│ └── ...
├── explore/ # Your script directory
│ └── Testsettings.py
└── ...
Tesettings.py
导入类错误
从Testsettings.py导入 ultralytics/utils 的class SettingManager
from ultralytics.utils.__init__ import SettingsManager
settings = SettingsManager()
File "d:\Code\ultralytics\Explore\TestSetting.py", line 15, in <module>
from ultralytics.utils.__init__ import SettingsManager
ModuleNotFoundError: No module named 'ultralytics'
PS D:\Code\ultralytics>
修改sys.path
查看sys.path,当前脚本仅从,以下目录中寻找import的类
import sys
print(sys.path)
"""
['d:\\Code\\ultralytics\\Explore',
'D:\\Software\\Miniconda3\\envs\\pytorchgpu\\python310.zip',
'D:\\Software\\Miniconda3\\envs\\pytorchgpu\\DLLs',
'D:\\Software\\Miniconda3\\envs\\pytorchgpu\\lib',
'D:\\Software\\Miniconda3\\envs\\pytorchgpu',
'D:\\Software\\Miniconda3\\envs\\pytorchgpu\\lib\\site-packages',
'D:\\Software\\Miniconda3\\envs\\pytorchgpu\\lib\\site-packages\\win32',
'D:\\Software\\Miniconda3\\envs\\pytorchgpu\\lib\\site-packages\\win32\\lib',
'D:\\Software\\Miniconda3\\envs\\pytorchgpu\\lib\\site-packages\\Pythonwin']
"""
添加路径,成功运行
添加整个project到sys.path路径中
import sys
import os
"""
__file______:current_file.py
"""
parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.append(parent_dir)
from ultralytics.utils.__init__ import SettingsManager
settings = SettingsManager()
print(sys.path)