How to pickle loggers?

后端 未结 5 1922
粉色の甜心
粉色の甜心 2021-02-14 22:17

Working on a project that requires that I am able to pickle the container object at any point, since we expect it to fail on external conditions quite frequently and be able to

5条回答
  •  生来不讨喜
    2021-02-14 22:26

    You could create a class that wraps the logger and implements __getstate__ and __setstate__.

    This is pasted from http://docs.python.org/library/pickle.html. The fh is handled in a way which may be similar to what you need.

    #!/usr/local/bin/python
    
    class TextReader:
        """Print and number lines in a text file."""
        def __init__(self, file):
            self.file = file
            self.fh = open(file)
            self.lineno = 0
    
        def readline(self):
            self.lineno = self.lineno + 1
            line = self.fh.readline()
            if not line:
                return None
            if line.endswith("\n"):
                line = line[:-1]
            return "%d: %s" % (self.lineno, line)
    
        def __getstate__(self):
            odict = self.__dict__.copy() # copy the dict since we change it
            del odict['fh']              # remove filehandle entry
            return odict
    
        def __setstate__(self, dict):
            fh = open(dict['file'])      # reopen file
            count = dict['lineno']       # read from file...
            while count:                 # until line count is restored
                fh.readline()
                count = count - 1
            self.__dict__.update(dict)   # update attributes
            self.fh = fh                 # save the file object
    

提交回复
热议问题