如何正确删除python抽象类中的lockfile?

时间:2017-09-11 17:37:23

标签: python python-3.x destructor single-instance lockfile

我有一个python3 cron脚本,由MyCron类和MyIMAP类组成。

MyCron类是一个抽象类,它确保只运行一个脚本实例。当cron在脚本运行时尝试运行脚本时,它会创建并销毁锁定文件并抛出SingleInstanceExeption

MyIMAP类继承MyCron类作为其基类。它会检查电子邮件并返回未读电子邮件。如果出现任何问题,我希望我的脚本能够整齐地关闭连接并销毁锁定文件。

在这两个课程中,我都要覆盖__del__方法。在MyCron,因为我需要删除锁定,并在MyIMAP中关闭连接。

当调用__del__时,我遇到了奇怪的结果(对象不再存在)。以下是代码示例:

class MyCron(object):
    def __init__(self, jobname=os.path.basename(sys.argv[0]).split('.')[0]):
        self.logger = logging.getLogger(__name__)
        self.initialized = False
        lockfilename  = "mycron"
        lockfilename += "-%s.lock" % jobname if jobname else ".lock"
        self.lockfile = os.path.normpath(tempfile.gettempdir() + '/' + lockfilename)
        self.logger.debug("MyCron lockfile: " + self.lockfile)
        self.fp = open(self.lockfile, 'w')
        self.fp.flush()
        try:
            fcntl.lockf(self.fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
            self.initialized = True
        except IOError:
            self.logger.warning("Another %s MyCron is already running, quitting." % jobname)
            raise SingleInstanceException()
            self.initialized = False

    def __del__(self):
        if not self.initialized:
            return
        try:
            fcntl.lockf(self.fp, fcntl.LOCK_UN)
            # os.close(self.fp)
            if os.path.isfile(self.lockfile):
                os.unlink(self.lockfile)
        except Exception as e:
            if self.logger:
                self.logger.warning(e)
            else:
                print("Unloggable error: %s" % e)
            sys.exit(-1)

class MyIMAP(MyCron):
    def __init__(self, server, username, password, port=993, timeout=60):
        super(MyIMAP, self).__init__()
        self.server     = server
        self.username   = username
        self.password   = password
        self.port       = port
        self.connection = None
        if self.initialized:
            socket.setdefaulttimeout(timeout)
            self.connect()
            self.login()

    def __del__(self):
        super(MyIMAP, self).__del__()
        if self.initialized and self.connection:
            self.connection.logout()
            self.logger.info("Close connection to %s:%d" % (self.server, self.port))

    ...

我理解这与__del__方法的不可预测性有关,我应该以不同的方式实现它。 python 3的最佳实践是什么?

0 个答案:

没有答案