Bootstrap FreeKB - Python (Scripting) - while loop
Python (Scripting) - while loop

Updated:   |  Python (Scripting) articles

while loop can be used to do something until a certain condition is true. 

For example.

#!/usr/bin/python3

attempt = 0

while attempt < 5:
  print(f"{attempt} is less than 5")
  attempt += 1

 

Should produce the following output.

0 is less than 5 
1 is less than 5 
2 is less than 5 
3 is less than 5 
4 is less than 5

 

Let's say you are passing a value into your Python script using argparse.

python3 example.py --count 3

 

In this scenario you would wrap int around arg.count.

#!/usr/bin/python3

attempt = 0

while attempt < int(arg.count):
  print(f"{attempt} is less than 5")
  attempt += 1

 

Here is a bit of a more practial example, where a while loop is used to attempt to start a Tomcat application server.

#!/usr/bin/python
import time

attempt = 0
running = False

while attempt < 5:
  ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("startup.sh")

  if any("http-nio-8080" in out for out in ssh_stdout):
    running = True
    break

  attempt += 1
  time.sleep(60)

if running == True:
  print("Tomcat appears to be up and running on port 8080")
else:
  print("Tomcat is NOT running on port 8080")

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 04dd12 in the box below so that we can be sure you are a human.