首页 > 解决方案 > 导入正确的模块但在 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_mainsrc/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'

我不明白这一点,因为我正在遵循确切的路径。

在此处输入图像描述

我不明白这一点,因为我走的是正确的道路。

标签: python

解决方案


在您的示例中,您将模块导入与DetectorDetector.class_coupling_detector位于同一目录中的文件中,但您的cwd不是src目录。

因此,您应该使用绝对导入from src.Detector...或相对导入from .Detector...

以下是有关这两种导入方式之间差异的一些信息


推荐阅读