I'm new to python, this below funtion is not getting stop at if condition where it needs to stop.
def check_pi_installation_status():
proc1cmd = "grep " AppName
p1 = subprocess.Popen(['kubectl', 'get', 'pi', '-A'], stdout=subprocess.PIPE)
p2 = subprocess.Popen(proc1cmd, shell=True, stdin=p1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p1.stdout.close()
stdout_list = p2.communicate()[0]
stdout_list = stdout_list.decode()
imagenamepi = stdout_list.split()
print("pi imagename ", imagenamepi)
if (imagenamepi[2] == 'Installed'):
print("Successfully Installed")
return
if (imagenamepi[2] == 'Failed'):
print(" Installation Failed")
return
if(imagenamepi[2] != 'Installed' and imagenamepi[2] != 'Failed'):
time.sleep(30)
# count = count 1
# print("count", count)
write_eventslog()
check_pi_installation_status()
Below are the case:
- when i started this function where its still not reached to 'Failed',it prints 'Installation Failed' on reaching state 'Failed' but it continues even when it reaches 'Failed' state.
- I ran the function when state is already 'Failed' its works as expected (it prints 'Installation Failed' and come out.
CodePudding user response:
Instead of using multiple if statements, why not use if, elif and else? The main difference here is that when you have multiple if statements, all of them will run no matter what, so change it to this:
if (imagenamepi[2] == 'Installed'):
print("Successfully Installed")
return
elif (imagenamepi[2] == 'Failed'):
print(" Installation Failed")
return
else:
time.sleep(30)
# count = count 1
# print("count", count)
write_eventslog()
check_pi_installation_status()
Over here, we first used if, then elif. elif is a mixture between IF and ELSE, which basically tells the compiler: If the statement above did not run, check this one. You can have multiple elif's in one go. Lastly, we have else. Else tells the compiler: If none of the other statements ran, run this one. Unlike Elif, you can only have one Else condition.
The main difference between the two methods are that when you use If, Elif and Else, the entire statement is exited when a condition is run.
Although im not too sure why return doesnt exit out the function immediately, the use of elif and else would help you do the same thing. More than likely, it works on the fail state because none of the other two statements are applicable.