如何使用def函数创建无限循环?

2024-09-27 00:11:46 发布

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

我写了一个程序,每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()

Tags: 文件importlogtimevarstdinopen单词
3条回答

使用while True

代码:

def func():
    while true:
        #Remaining function

有关^{} look in to this SO question的更多信息

while True将永远运行您必须使用Ctrl+c或在循环内使用break来停止它

你可以用无限循环

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: maximum recursion depth exceeded

因为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-Ckill)。也许值得重新考虑一下,这样你就可以以更干净的方式关闭它。在

相关问题 更多 >

    热门问题