0

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?

rish_hyun
  • 451
  • 1
  • 7
  • 13
  • 1
    Check https://stackoverflow.com/questions/1481488/what-is-the-del-method-how-to-call-it – buran Apr 22 '21 at 17:51
  • 2
    Seems like it'd be much easier to write your class as a context manager rather than try to hack the "close" behavior with `__del__` – BallpointBen Apr 22 '21 at 17:52
  • @buran`del obj` Worked for me! Thanks for suggesting this answer – rish_hyun Apr 22 '21 at 17:55
  • @BallpointBen That's a nice idea too! – rish_hyun Apr 22 '21 at 17:56
  • @rish_hyun - you completely misunderstood me. Don't hack `__del__` for close behaviour. – buran Apr 22 '21 at 17:57
  • Also if this is not some school project why not use `logging` module or some other logging tools available? – buran Apr 22 '21 at 17:58
  • @buran No! That's not what I meant, I meant that I shall close the file by calling a function rather than depending on `__del__` – rish_hyun Apr 22 '21 at 17:59
  • @buran NO, it's not a school project, I am preparing a software :) I have saw `logging` but I want to make my own – rish_hyun Apr 22 '21 at 17:59
  • You lost me with _`del obj` Worked for me_ – buran Apr 22 '21 at 18:02
  • @buran Well, `del obj` worked for me SO I am happy :) and I am going with it – rish_hyun Apr 22 '21 at 18:02
  • do whatever you want but my advise is not to use `del obj` and `__del__` for what you are doing - that was my point. You clearly don't understand the `__del__` [special method](https://docs.python.org/3/reference/datamodel.html#object.__del__). – buran Apr 22 '21 at 18:05
  • @buran Oh!! okay, That's was also given in https://stackoverflow.com/questions/1481488/what-is-the-del-method-how-to-call-it that '__del__' shouldn't be use , so I shall not use `__del__` and `del` for destroying objects. Actually, I thoroughly gone through it now – rish_hyun Apr 22 '21 at 18:07

0 Answers0