python - 导入正确的模块但在 python 中出现错误
问题描述
import sys
from subprocess import run, PIPE
import shlex
from src.detector_main import detect_main
def main():
# print command line arguments
for arg in sys.argv[1:]:
print(arg)
if __name__ == "__main__":
# main()
print(sys.argv)
这是我的主要模块。如果您看到from src.detector_main import detect_main
,它应该是从 导入detect_main
的src/detector_main.py
。
在我的detector_main.py
,我有一堆进口,
import ast
import os
import fpdf
import sys
from Detector.class_coupling_detector import detect_class_cohesion
from Detector.cyclomatic_complexity_detector import detect_cyclomatic_complexity
from Detector.long_lambda_detector import detect_long_lambda
from Detector.long_list_comp_detector import detect_long_list_comp
from Detector.pylint_output_detector import detect_pylint_output
from Detector.shotgun_surgery_detector import detect_shotgun_surgery
from Detector.useless_exception_detector import detect_useless_exception
# from tools.viz_generator import add_viz
def detect_main(directory):
# Get stats for files in directory
stats_dict = get_stats(directory)
....
运行我的主模块给了我这个错误:
File "pyscent.py", line 5, in <module>
from src.detector_main import detect_main
File "C:\Users\user\Desktop\proj\src\detector_main.py", line 5, in <module>
from Detector.class_coupling_detector import detect_class_cohesion
ModuleNotFoundError: No module named 'Detector'
我不明白这一点,因为我正在遵循确切的路径。
我不明白这一点,因为我走的是正确的道路。
解决方案
在您的示例中,您将模块导入与DetectorDetector.class_coupling_detector
位于同一目录中的文件中,但您的cwd不是src目录。
因此,您应该使用绝对导入from src.Detector...
或相对导入from .Detector...
以下是有关这两种导入方式之间差异的一些信息
推荐阅读
- sql - 在事务期间更新依赖表时出现“外键约束失败”
- javascript - 动作必须具有类型属性
- python - Repartition() 导致火花作业失败
- apache - 让 .htaccess 从一个域重定向到另一个域以适用于 WWW(http://www. 和 https://www.)、HTTP 和 HTTPS
- python - PyTorch 中具有模型并行性的共享权重
- angular - 如果它在角度中具有空值,则绕过
- ios - Obj-C-检测textView换行符?
- php - 如何从不同的数据库表中选择行而不以任何方式连接它们并在循环中显示结果
- javascript - 如何在提示之前进行样式更改
- spring - Spring存储过程的通用包装器