我有一个由一个MyCron
类和一个MyIMAP
类组成的 python3 cron 脚本。
该类MyCron
是一个抽象类,可确保只有一个脚本实例运行。它创建和销毁一个锁定文件,并SingleInstanceExeption
在 cron 在脚本已经运行时尝试运行该脚本时抛出一个。
该类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的最佳实践是什么?