I have made a Class
import os
import math
from datetime import datetime
class Log:
def __init__(self, file_name):
self.log_name = f"{file_name}.log"
self.log = open(os.path.abspath(self.log_name), 'a+')
if os.stat(self.log_name).st_size == 0:
self.add_log('START')
def __del__(self):
try:
self.add_log('FINISH')
self.log.close()
except Exception as e:
print(e)
def add_log(self, text):
self.log.write(f"{self.now()} {self.message(text)}\n")
self.log.flush()
os.fsync(self.log)
def now(self):
return str(datetime.now().strftime('%d-%m-%Y %H:%M:%S'))
def message(self, text):
tot_len = 70
ret_text = str(f"[{'-'*tot_len}]")
return ret_text[:(tot_len//2)-(len(text)//2)] + text + ret_text[(tot_len//2)+math.ceil(len(text)/2):]
The purpose of my class is to create logs.
In another file, let's say demo.py
, I imported this
from log import Log
obj = Log('demo01')
obj.add_log('THis is line 1')
obj.add_log('THis is line 2')
obj.add_log('THis is line 3')
obj.add_log('THis is line 4')
obj.add_log('THis is line 5')
I have got a file demo01.log
in which
22-04-2021 23:08:44 [--------------------------------START---------------------------------]
22-04-2021 23:08:44 [---------------------------THis is line 1-----------------------------]
22-04-2021 23:08:44 [---------------------------THis is line 2-----------------------------]
22-04-2021 23:08:44 [---------------------------THis is line 3-----------------------------]
22-04-2021 23:08:44 [---------------------------THis is line 4-----------------------------]
22-04-2021 23:08:44 [---------------------------THis is line 5-----------------------------]
So, here comes the last part, the __del__
raise an exception
import of time halted; None in sys.modules
and
FINISH
doesn't print in last line
So basically, I understood that sys
get out of scope (I am guessing this has happen, correct me if I am wrong)
So, what could be solution for __del__
to work without exception?