为什么ModuleNotFoundError:Python文件中没有名为“异常”的模块

问题描述 投票:0回答:1

我有这样的文件夹结构:

src/
|__ __init__.py
|__ exception.py
|__ logger.py
|__ components/
   |__ __init__.py
   |__ data_ingestion.py

两个 init.py 都是空的。

当我运行命令“python src/components/data_ingestion.py”时,它给我错误:

两个 init.py 文件都是空的。当尝试运行命令“python src/components/data_ingestion.py”时,我遇到了错误。该项目由三个主要文件组成:Exception.py、logger.py 和 data_ingestion.py。 data_ingestion.py 文件正在尝试从 exception.py 和 logger.py 导入类。

这里是代码:

异常.py

import sys
from logger import logging

def error_message_detail(error,error_detail:sys):
    _,_,exc_tb = error_detail.exc_info()
    file_name = exc_tb.tb_frame.f_code.co_filename

    error_message = "Error occured in python script name [{0}] line number [{1}] error message [{2}]".format(
        file_name, exc_tb.tb_lineno, str(error)
    )

    return error_message

class CustomException(Exception):
    
    def __init__(self, error_message, error_detail:sys):
        super().__init__(error_message)
        self.error_message = error_message_detail(error_message, error_detail=error_detail)

    def __str__(self):
        return self.error_message  
    

if __name__=="__main__":
    logging.info("Logging has started")

    try:
        a=1/0
    except Exception as e:
        logging.info('Division by zero') 
        raise CustomException(e,sys)

logger.py

import logging 
import os
from datetime import datetime

LOG_FILE=f"{datetime.now().strftime('%m_%d_%Y_%H_%M_%S')}.log"
logs_path=os.path.join(os.getcwd(),"logs",LOG_FILE)
os.makedirs(logs_path,exist_ok=True)

LOG_FILE_PATH=os.path.join(logs_path,LOG_FILE)

logging.basicConfig(
    filename=LOG_FILE_PATH,
    format="[ %(asctime)s ] %(lineno)d %(name)s - %(levelname)s - %(message)s",
    level=logging.INFO
)

##### The below code is only for checking and not required
if __name__=="__main__":
    logging.info("Logging has started")

data_ingestion.py

from src.exception import CustomException
from src.logger import logging

请帮忙

python python-3.x compiler-errors runtime-error
1个回答
0
投票

您正在尝试从(子)模块内运行脚本,并且该模块正在尝试调用其父模块中的函数。在这种情况下,子模块对父模块一无所知。

另一方面,如果您最初从父模块运行应用程序,则此导入将起作用。

以您的树结构为例,在父模块中创建一个python文件:

src/
|__ __init__.py
|__ main.py  <== new file
|__ exception.py
|__ logger.py
|__ components/
   |__ __init__.py
   |__ data_ingestion.py

然后从

main.py
你将能够调用
data_ingestion.py
内部的任何函数,而他们反过来也会了解
exception.py
logger.py
内部的函数。

© www.soinside.com 2019 - 2024. All rights reserved.