import threading
import os
class LockedFile(object):
SETUP_LOGGER_LOCK = threading.Lock()
LOGFILES = {}
@classmethod
def open(cls, fn):
with cls.SETUP_LOGGER_LOCK:
if fn not in cls.LOGFILES:
if os.path.exists(os.path.dirname(fn)):
os.mkdir(os.path.dirname(fn))
cls.LOGFILES[fn] = cls(fn)
rv = cls.LOGFILES[fn]
rv.users += 1
return rv
def __init__(self, fn):
self._filename = fn
self._f = None
self.users = 0
self._lock = threading.Lock()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def write(self, data):
with self._lock:
if self._f is None:
self._f = open(self._filename, ‘ab‘)
self._f.write(data)
self._f.flush()
def close(self):
with self.SETUP_LOGGER_LOCK:
self.users -= 1
if self.users == 0:
if self._f:
self._f.close()
self.LOGFILES.pop(self._filename)
原文:https://www.cnblogs.com/Ghostant/p/14656642.html