I am trying to get a simple progress bar working in my Python container on Kubernetes. However, it doesn't output anything until the job is done and the progress bar reaches 100%. The same exact code works perfectly in a local Docker container. So what is it that Kubernetes has in place that prevents me from seeing the progress bar updating in real time in its logs?
Progress bar code:
import sys
import time
class Color:
BOLD = '\033[1m'
ENDC = '\033[0m'
ERASE_LINE = '\x1b[2K\r'
def percentage(current, total):
percent = 100 * float(current) / float(total)
return percent
class ProgressBar:
def __init__(self, total):
self._total = total
self._current = 0
self.print()
def update(self):
self._current += 1
self.print()
def print(self):
percent = percentage(self._current, self._total)
sys.stdout.write("\r")
sys.stdout.write(Color.BOLD + "[%-50s] %d%%" % ('=' * int(percent / 2), percent) + Color.ENDC)
sys.stdout.flush()
if __name__=="__main__":
print("Ready to run soon...")
time.sleep(10)
print("Running!")
pbar = ProgressBar(255)
for i in range(255):
time.sleep(0.03)
pbar.update()
When logging, rather than displaying things in a TTY to a human, you generally need to log in complete lines ending in \n
. Rather than a progress bar, I would usually recommend something like printing out 10%...\n20%...\n etc
. Up to you how often you print the current state.
Update:
You can update your script to detect if the terminal is TTY, and change the behaviour accordingly
Use this:
import os, sys
if os.isatty(sys.stdout.fileno()):