簡體   English   中英

Python 隨機跳過循環迭代

[英]Python skips for loop iterations randomly

在編寫Python代碼時,我是一個相對新手。 這是我的問題,我正在重新啟動服務器,需要驗證服務是否已重新啟動。 服務器恢復聯機后,我運行命令並將輸出存儲到 txt。 然后我針對 txt 文檔啟動一個 for 循環,確保服務已啟動。 然而,有時會跳過 for 循環而不是其他循環。

def verify_serv():
    print ("start verif placeholder")#for troubleshooting 

    txtdoc = open('output2.txt','r')
    regexp = re.compile(r'\[STARTING\]')
    regexp2 = re.compile(r'\[STARTED\]')

    for line in txtdoc:
        match = regexp.match(line)
        nomatch = regexp2.match(line)
        print('in for loop')#for troubleshooting 
        if match:
            print ('in if loop')#for troubleshooting 
            print ('Still Starting \n\n\n\n\n\n')# testing only
            time.sleep(5)
            break
        elif nomatch:
            print('Done')
            end_email()


    txtdoc.close()     
    os.remove('output2.txt')

    print('end loop')#for troubleshooting 
    match = None
    nomatch = None
    txtdoc = None
    time.sleep(60)
    command_2()# pull new output file to recheck

我還將添加一些輸出。

admin:#This iteration Skips Loop
starting verification
start verif placeholder
end loop

starting verification# This iteration enters loop
start verif placeholder
in for loop #x91
in if loop
Still Starting 






end loop

admin: # loop Completes Services Restated
starting verification
start verif placeholder
in for loop #x80
Done

上面的例子顯示了正確的結果,但有時代碼會在沒有完成的情況下運行。

任何幫助將非常感激。

這里有一個“競爭條件”:如果在服務啟動(甚至開始啟動)之前打開文件,文件將為空,因此for循環將結束。 您通過睡眠獲得了正確的想法,但您必須將其置於第二個循環中,因此您將重新打開文件並再次檢查。 像這樣的東西:

def verify_serv():
    # Infinite loop to keep checking the file
    while True:
        # The `with` block ensures the file will be closed automatically
        with open('output2.txt') as f:
            for line in f:
                if '[STARTED]' in line:
                    # It's started, so we're done
                    return

        # But if we got here, it hasn't started yet, so sleep and try again
        time.sleep(5)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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