我想替换 Cron Jobs 以“保持”我的程序事件,因为它会调用每个 XX 间隔,无论脚本是否已被调用,从而创建重复的条目。
我调查了这个问题,并提出了一些方法。一个是修改我的程序,以便它检查它是否已经被调用并自行关闭。我采用的方法是通过使用 execfile 一遍又一遍地调用自身,将其与 Cronjob 完全分离,这完全符合我的要求,除了以下问题: RuntimeError:超出最大递归深度
有没有办法让程序保持在“无限循环”中而不会出现 Stack Overflow?
这是我的代码,它是一个检查邮件并将其转换为 MySQL 数据库条目的程序。
imap = imaplib.IMAP4(hst)
try:
imap.login(usr, pwd)
except Exception as e:
errormsg = e
time.sleep(30)
print "IMAP error: " + str(errormsg)
execfile('/var/www/html/olotool/converter.py')
raise IOError(e)
# Authentification & Fetch Step
while True:
time.sleep(5)
'''
The script will always result in an error if there
are no mails left to check in the inbox. It then
goes into sleep mode and relaunches itself to check
if new mails have arrived.
'''
try:
imap.select("Inbox") # Tell Imap where to go
result, data = imap.uid('search', None, "ALL")
latest = data[0].split()[-1]
result, data = imap.uid('fetch', latest, '(RFC822)')
raw = data[0][1] # This contains the Mail Data
msg = email.message_from_string(raw)
except Exception as e:
disconnect(imap)
time.sleep(60)
execfile('/var/www/html/olotool/converter.py')
raise IOError(e)
请您参考如下方法:
我用我现在认为可行的唯一方法自己解决了这个问题。 首先,我更改了上面代码中的异常:
except Exception as e:
disconnect(imap)
print "Converter: No messages left"
raise os._exit(0)
# This is a special case since this Exception is
# no error thus os._exit(0) gives no false-positives
如您所见,我现在不再使用 execfile。相反,我编写了一个 Controller 脚本来检查我的 converter.py 的状态并在它尚未运行时启动它:
while True:
presL = os.popen('pgrep -lf python').read()
print "________________________________________"
print "Starting PIDcheck"
print "Current Processes: "
print presL # Check Processes
presRconverter = find('\d{7} python converter.py', presL)
if presRconverter:
# Store the PID
convPID = find('\d{7}', presRconverter)
print "Converter is running at PID: " + convPID
else:
print "PID Controller: Converter not running"
try:
print "PID Controller: Calling converter"
subprocess.check_call('python converter.py', shell=True)
except subprocess.CalledProcessError as e:
errormsg = e
print "Couldn't call Converter Module"
sendMail(esender,ereceiver,esubject,etext,server)
print "Error notification send"
raise IOError(e)
# If we got until here without ERROR, the call was Successfull
print "PID Controller: Call successful"
print "________________________________________"
time.sleep(60)
此方法不会引发:RuntimeError: maximum recursion depth exceeded。如果您使用命令 nohup python converter.py 运行 Controller ,这还会为您提供一个 nohup.out 文件,您可以在其中看到任何错误处理问题。
我希望我能帮助遇到同样问题的任何人。
