[英]How do i make a infinite loop with def function?
我编写了一个程序,该程序每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()
你可以像这样使用无限循环
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)
这个错误
RuntimeError:超过最大递归深度
您得到了,因为alarm()
函数的无限递归调用。 每个递归调用都需要一定数量的堆栈内存。 堆栈空间是有限的,在经过一定数量的递归调用后,堆栈将溢出。 为了防止这种情况, Python限制了最大递归深度。
就您而言,您根本不需要递归。
每次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)
但是,请记住,结束该程序的唯一方法是将其终止(例如,使用CTRL-C或kill
)。 可能值得重新考虑一下,以便您以更清洁的方式关闭它。
while True
使用
码:
def func():
while true:
#Remaining function
有关while loop
更多信息while loop
查看此SO问题
while True
会永远运行,您必须使用Ctrl+c
或在循环内使用break
来停止它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.