Python随机跳过循环迭代

Python随机跳过循环迭代,python,Python,我是编写Python代码的新手。这是我的问题,我正在重新启动服务器,需要验证服务是否已重新启动。一旦服务器恢复联机,我运行一个命令并将输出存储到txt。然后,我针对txt文档启动for循环,确保服务已启动。但是,有时会跳过for循环,而不是其他循环 def verify_serv(): print ("start verif placeholder")#for troubleshooting txtdoc = open('output2.txt','r') regex

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

格式化您的代码,请更具体一点,我会添加一个“else”和您可以看到的输出。看起来它既不符合if条件,也不符合elif条件。也许可以添加其他选项:打印“匹配”,匹配并打印“nomatch”,nomatch以查看结果