Python随机跳过循环迭代

2024-09-24 12:21:31 发布

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

我是编写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

上面的例子显示了一个正确的结果,但有时代码只会运行而没有完成。你知道吗

任何帮助都将不胜感激。你知道吗


Tags: intxtloopforifmatchlinestart
1条回答
网友
1楼 · 发布于 2024-09-24 12:21:31

这里有一个“竞争条件”:如果在服务启动(甚至开始启动)之前打开文件,文件将为空,因此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)

相关问题 更多 >