Last active
August 5, 2024 19:12
-
-
Save ivarref/3fd164fd12fb88443f2b416eac61c22c to your computer and use it in GitHub Desktop.
apt-get progress bar
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# based on https://mdk.fr/blog/how-apt-does-its-fancy-progress-bar.html | |
# to run: python -u ./demo.py | |
# notice the -u for unbuffered | |
import time | |
import os | |
from datetime import datetime | |
columns, lines = os.get_terminal_size() | |
def write(s): | |
print(s, end="") | |
time.sleep(0.2) | |
write("\n") # Ensure the last line is available. | |
write("\0337") # Save cursor position | |
write(f"\033[0;{lines-1}r") # Reserve the bottom line | |
write("\0338") # Restore the cursor position | |
write("\033[1A") # Move up one line | |
try: | |
for i in range(250): | |
time.sleep(0.2) | |
write(f"Hello {i}") | |
write("\0337") # Save cursor position | |
write(f"\033[{lines};0f") # Move cursor to the bottom margin | |
write(datetime.now().isoformat()) # Write the date | |
write("\0338") # Restore cursor position | |
write("\n") | |
except KeyboardInterrupt: | |
pass | |
finally: | |
write("\0337") # Save cursor position | |
write(f"\033[0;{lines}r") # Drop margin reservation | |
write(f"\033[{lines};0f") # Move the cursor to the bottom line | |
write("\033[0K") # Clean that line | |
write("\0338") # Restore cursor position |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment