簡體   English   中英

如何使用def函數進行無限循環?

[英]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-Ckill )。 可能值得重新考慮一下,以便您以更清潔的方式關閉它。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM