如何使用def函数进行无限循环?

ADT*_*ank 0 python function infinite-loop

我编写了一个程序,每5秒检查一个日志文件以获取一个特定的单词.当它发现该字时会产生一些噪音并覆盖日志文件.我得到的问题是:

RuntimeError:调用Python对象时超出了最大递归深度.

有没有更好的方法来制作这个循环?

import time
import subprocess
global playalarm

def alarm():
    if "No answer" in open("/var/log/hostmonitor.log").read():
        print "Alarm!"
        playalarm=subprocess.Popen(['omxplayer','/root/Alarm/alarm.mp3'],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,close_fds=True)
        log = open("/var/log/hostmonitor.log","w")
        log.write("Checked")
        log.close()
        time.sleep(5)
        playalarm.stdin.write('q')
        alarm()
    else:
        print"Checked"
        time.sleep(5)
        alarm()

alarm()
Run Code Online (Sandbox Code Playgroud)

kvo*_*iev 6

你可以像使用无限循环一样

def alarm():
    while True:
        if "No answer" in open("/var/log/hostmonitor.log").read():
            print "Alarm!"
            playalarm=subprocess.Popen(['omxplayer','/root/Alarm/alarm.mp3'],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,close_fds=True)
            log = open("/var/log/hostmonitor.log","w")
            log.write("Checked")
            log.close()
            time.sleep(5)
            playalarm.stdin.write('q')
        else:
            print"Checked"
            time.sleep(5)
Run Code Online (Sandbox Code Playgroud)

这个错误

RuntimeError:超出最大递归深度

你得到因为alarm()函数的无穷递归调用.每次递归调用都需要一定量的堆栈内存.堆栈空间是有限的,经过一定数量的递归调用后,堆栈将溢出.为了防止这种情况,Python限制了递归的最大深度.
在您的情况下,您根本不需要递归.


pax*_*blo 5

每次alarm()调用自己时,你会使用更多的堆栈空间,最终耗尽,因为供应不是无限的.

你需要的是一个循环:

def alarm():
    while True:
        if "No answer" in open("/var/log/hostmonitor.log").read():
            print "Alarm!"
            playalarm=subprocess.Popen(['omxplayer','/root/Alarm/alarm.mp3'],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,close_fds=True)
            log = open("/var/log/hostmonitor.log","w")
            log.write("Checked")
            log.close()
            time.sleep(5)
            playalarm.stdin.write('q')
        else:
            print"Checked"
            time.sleep(5)
Run Code Online (Sandbox Code Playgroud)

但是你应该记住,结束该程序的唯一方法就是杀掉它(例如,用CTRL-C或者kill).重新思考它可能是值得的,这样你就可以以更清洁的方式关闭它.