Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- ###########################
- This program demonstrates how to do a progress bar for your program in Python CLI. It uses ASCII escape strings, with string formatted print statements to move the cursor to the correct position at the end of every 3-line print job. Also works with any sized terminal, since it determines the width, then calculates how many of each character to print.
- ###########################
- '''
- from __future__ import print_function
- import sys
- import time
- import math
- def get_terminal_size(fd=1):
- """
- Returns height and width of current terminal. First tries to get
- size via termios.TIOCGWINSZ, then from environment. Defaults to 25
- lines x 80 columns if both methods fail.
- :param fd: file descriptor (default: 1=stdout)
- """
- try:
- import fcntl, termios, struct
- hw = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
- except:
- try:
- hw = (os.environ['LINES'], os.environ['COLUMNS'])
- except:
- hw = (25, 80)
- return hw
- def get_terminal_height(fd=1):
- """
- Returns height of terminal if it is a tty, 999 otherwise
- :param fd: file descriptor (default: 1=stdout)
- """
- if os.isatty(fd):
- height = get_terminal_size(fd)[0]
- else:
- height = 999
- return height
- def get_terminal_width(fd=1):
- """
- Returns width of terminal if it is a tty, 999 otherwise
- :param fd: file descriptor (default: 1=stdout)
- """
- if os.isatty(fd):
- width = get_terminal_size(fd)[1]
- else:
- width = 999
- return width
- height, width = get_terminal_size()
- i = 0
- while i < 100:
- i += .13
- if i > 100: i = 100
- spaces = int((((width-10)*i/100)))
- print("%s%s%s" % ("|", "-" * (width-2), "|"))
- if i < 100:
- print("|%6.2f %% " % (i), end="")
- print("%s%s%s" % (u"\u2588" * min(width-11, (spaces)), " " * (width-spaces-11), "|"), end="\n")
- if i == 100:
- print("|%6.0f %% " % (i), end="")
- print("%s%s" % (u"\u2588" * (width-11), "|"), end="\n")
- print("%s%s%s" % ("|", "-" * (width-2), "|"))
- # This is just to show you progress over a set time. Normally this would not be included.
- time.sleep(.0125)
- # You don't want this printed at the end so it doesn't move the cursor back up. It moves the cursor X
- # lines up for number N in the <>
- if i < 100:
- print("\033[<3>A", end="\r")
- sys.stdout.flush()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement