我有这样的文件夹结构:
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文件:
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
内部的函数。