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

无限运行的服务器端python脚本?,python,python-2.7,loops,recursion,rhel,Python,Python 2.7,Loops,Recursion,Rhel,我想替换Cron作业来“保持”我的程序处于活动状态,因为无论是否已经调用了scrip,它都会每隔XX个间隔调用一次,从而创建重复的条目 我调查了这个问题,并提出了一些方法。一个是修改我的程序,让它检查它是否已经被调用并自动关闭。我所追求的是,通过反复使用execfile调用自身,将其与Cronjob完全分离,这正是我想要的,除了以下问题: 运行时错误:超过最大递归深度 有没有一种方法可以让程序保持在“无限循环”中,而不会出现堆栈溢出 这是我的代码,它是一个检查邮件并将其转换为MySQL DB条目

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

我调查了这个问题,并提出了一些方法。一个是修改我的程序,让它检查它是否已经被调用并自动关闭。我所追求的是,通过反复使用
execfile
调用自身,将其与Cronjob完全分离,这正是我想要的,除了以下问题:
运行时错误:超过最大递归深度

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

这是我的代码,它是一个检查邮件并将其转换为MySQL DB条目的程序

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
。相反,我编写了一个控制器脚本,用于检查我的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)
此方法不会引发:
运行时错误:超过最大递归深度
。此外,如果您使用命令
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。

我不明白您为什么在没有邮件的情况下引发异常,然后重新启动脚本。为什么不检查新电子邮件,然后仅在
结果
数据
不为空时处理邮件?如果您想让它永远运行,一个简单的
while True
以及对可能的数据结果进行错误检查就足够了。如果需要某种脚本管理,可以使用supervisord确保脚本正在运行,并在脚本发生意外错误时重新启动。无法仅检查新邮件,因为人们正在使用该收件箱,我每天会收到20多种不同类型的邮件进入收件箱+/-2000,并且必须检查每一封邮件是否需要处理。上面的脚本只是一小部分,脚本是如何开始的,完成后应该如何结束。基本上,我需要检查一大堆东西,然后将条目写入MySQLdb。我知道我的方法很糟糕,但我必须从某个地方开始。