在编写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
以上情况显示了正确的结果,但有时代码将仅运行而未完成。
任何帮助将不胜感激。
答案 0 :(得分:0)
您在这里有一个“竞争条件”:如果在服务启动之前(甚至开始启动)打开文件 ,该文件将为空,因此for
循环会停。您可以通过睡觉来获得正确的主意,但是您必须将其放入 second 循环中,因此您将重新打开该文件并再次检查它。像这样:
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)