Python 如何使用def函数生成无限循环?

Python 如何使用def函数生成无限循环?,python,function,infinite-loop,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():

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

运行时错误:超过最大递归深度

因为无限次递归调用
alarm()
函数,所以可以得到。每个递归调用都需要一些堆栈内存。堆栈空间是有限的,经过一定数量的递归调用后,堆栈将溢出。为了防止这种情况,Python限制递归的最大深度。

在您的情况下,根本不需要递归。

使用
,而使用True

代码:

def func():
    while true:
        #Remaining function
更多关于

虽然True
将永远运行,但您必须在循环中使用
Ctrl+c
或使用
break
来停止它

每次
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
)。也许值得重新考虑一下,这样您就可以更干净地关闭它。

您所认为的函数的“局部作用域”存储在一个数据结构中,该数据结构在输入方法时被推到堆栈上,在方法退出时被弹出。由于您无限地调用alarm函数,没有任何调用完成,因此您超过了最大堆栈深度(有限),并看到此错误。简单的解决方法是使用循环而不是递归。是的,但是程序应该运行并且永远不会停止。谢谢你的回答。while true的解释非常有用,谢谢。