无限运行的服务器端python脚本?

2024-04-26 03:20:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我想替换Cron作业来“保持”程序的活动状态,因为无论是否已经调用了脚本,它都会每隔XX个间隔调用一次,从而创建重复的条目。在

我调查了这个问题,并有一些方法。如果我的程序已经被调用来修改它自己。我所追求的是通过一次又一次地用execfile调用它自己,将它与Cronjob完全分离,除了以下问题: RuntimeError: maximum recursion depth exceeded

有没有一种方法可以让程序保持在“无限循环”中而不会出现堆栈溢出?在

这是我的代码,它是一个检查邮件并将其转换为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)

Tags: to方法程序datatimeasexceptionsleep
2条回答

我自己解决了这个问题,我认为这是目前唯一可能的办法。 首先,我在上面的代码中更改了我的异常:

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。相反,我编写了一个控制器脚本来检查转换器.py并在尚未运行时启动它:

^{pr2}$

此方法不引发:RuntimeError: maximum recursion depth exceeded。此外,如果您使用命令nohup python converter.py运行控制器,则会提供一个nohup.out文件,在该文件中可以看到错误处理的任何问题。在

我希望我能帮助任何遇到同样问题的人。在

在不必借助子流程检查的情况下,应该可以按照这种思路工作:

def check_mail_loop():
    imap = imaplib.IMAP4(hst)
    # Build some function to login, and, in the event of an error, sleep for n seconds and call login function again.
    imap.login(usr, pwd)

    while True:
        try:
            imap.select("Inbox")
            result, data = imap.uid('search', None, "ALL")

            if result and data:
                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)
            time.sleep(5)
        except SomeRelevantException as e:
            logging.log(e)
            time.sleep(60)
            pass

在发生一些你没有预见到的随机错误时,使用一个过程控制管理器,比如supervisord或monit。在

相关问题 更多 >