我写了一个程序,每5秒检查一次日志文件中的某个特定单词。 当它找到那个单词时,它会发出一些噪音并覆盖日志文件。 问题是在某一点之后我得到:
RuntimeError: maximum recursion depth exceeded while calling a Python object.
有没有更好的方法来做这个循环?在
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()
使用
while True
代码:
有关^{} look in to this SO question 的更多信息
while True
将永远运行您必须使用Ctrl+c
或在循环内使用break
来停止它你可以用无限循环
这个错误
因为
alarm()
函数的无限递归调用。每个递归调用都需要一定量的堆栈内存。堆栈空间是有限的,经过一定数量的递归调用后,堆栈将溢出。为了防止这种情况,Python限制了递归的最大深度。在你的例子中,你根本不需要递归。在
每次
alarm()
调用自身时,都会使用多一点的堆栈空间,最终会耗尽,因为供应不是无限的。在相反,您需要的是一个沿着以下路线的循环:
但您应该记住,结束该程序的唯一方法是关闭它(例如使用CTRL-C或
kill
)。也许值得重新考虑一下,这样你就可以以更干净的方式关闭它。在相关问题 更多 >
编程相关推荐