Python (Scripting) - while loop

by
Jeremy Canfield |
Updated: March 23 2024
| Python (Scripting) articles
A 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