v0mit

Untitled

Oct 18th, 2011
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.35 KB | None | 0 0
  1. #! /usr/bin/env python
  2. # Filename: ConsoleUtils.py
  3.  
  4. import sys
  5.  
  6. __version__ = "v1.0a"
  7. __author__ = "Ki113d"
  8. __maintainer__ = "Ki113d"
  9. __email__ = "[email protected]"
  10. __status__ = "Development"
  11.  
  12. class ProgressBar():
  13.     """
  14.        A console based progress bar.
  15.        Used to give a visual representation on the progress of an
  16.        opperation.
  17.    """
  18.    
  19.     def __init__(self, message="", fillChar='-'):
  20.         """
  21.            Constructor.
  22.            Params:
  23.                message: A string describing the current opperation or nothing.
  24.                fillChar: The character used to display progress on the bar.
  25.        """
  26.         self.char = fillChar
  27.         self.message = message
  28.         self.bar = ''
  29.         self.length = 20
  30.         self.createBar()
  31.                
  32.     def updateBar(self, percentage):
  33.         """
  34.            This method should be called by the user to update the progress bar.
  35.            When the threaded version is released it will be more efficient.
  36.        """
  37.         if not isinstance(percentage, int):
  38.             raise ValueError("Percentage must be of type int!")
  39.            
  40.         if percentage > -1 and percentage < 101:
  41.             self.calculateBar(percentage)
  42.             self.write("{0}[{1}]{2:4}%".format(self.message + " ", self.bar, percentage))
  43.         else:
  44.             if percentage < 0:
  45.                 raise ValueError("Percentage must never be lower then 0!")
  46.             elif percentage > 100:
  47.                 raise ValueError("Percentage must never be greater then 100!")
  48.    
  49.     def write(self, line):
  50.         """
  51.            Writes the given line to stdout.
  52.            May support other outputs later.
  53.        """
  54.         sys.stdout.write("{0}\r".format(line))
  55.         sys.stdout.flush()
  56.        
  57.     def calculateBar(self, percent):
  58.         """
  59.            Changes the state of the progress bar according to the given
  60.            percentage.
  61.            Will be worked on later to support different sized progress bars.
  62.        """
  63.         i = 0
  64.         parts = list(self.bar)
  65.         while i < (percent/5):
  66.             parts[i] = self.char
  67.             i += 1
  68.         self.bar = "".join(parts)
  69.    
  70.     def createBar(self):
  71.         """
  72.            Constructs the progress bar.
  73.            Will be used in the future to enable different sized progress bars.
  74.        """
  75.         i = 0
  76.         while i < self.length:
  77.             self.bar += " "
  78.             i += 1
  79.            
  80.     def close(self):
  81.         """
  82.            Prints a new line to close off use of stdout.
  83.            This method must be called or any output from your
  84.            application may cause trouble.
  85.        """
  86.         print()
  87.  
  88. class LoadingLabel():
  89.     """
  90.        A LoadingLabel (for lack of a better name).
  91.        Used to give a nice visual representation that your program is
  92.        doing something.
  93.    """
  94.    
  95.     def __init__(self, message=("Loading", "Loading.", "Loading..", "Loading..."), closingString="Done!"):
  96.         """
  97.            Constructor.
  98.            Params:
  99.                message: A tuple containing strings to be displayed.
  100.        """
  101.         if not isinstance(message, tuple):
  102.             raise ValueError("Message must be of type tuple!")
  103.         self.message = message
  104.         self.closingString = closingString
  105.         self.currentIndex = 0
  106.         self.lastIndex = 0
  107.    
  108.     def write(self, line):
  109.         """
  110.            Writes the given line to stdout.
  111.            May support other outputs later.
  112.        """
  113.         sys.stdout.write("{0}\r".format(line))
  114.         sys.stdout.flush()
  115.        
  116.     def update(self):
  117.         """
  118.            Updates the LoadingLabel and moves to the next indexed string in the tuple.
  119.        """
  120.         self.write("{0:{1}}".format(self.message[self.currentIndex], len(self.message[self.lastIndex])))
  121.         self.lastIndex = self.currentIndex
  122.         if self.currentIndex == len(self.message)-1:
  123.             self.currentIndex = 0
  124.         else:
  125.             self.currentIndex += 1
  126.        
  127.     def close(self):
  128.         """
  129.            Prints closing string and a new line to close off use of stdout.
  130.            This method must be called or any output from your
  131.            application may cause trouble.
  132.        """
  133.         self.write("{0:{1}}".format(self.closingString, len(self.message[self.currentIndex])))
  134.         print()
  135.            
  136. if __name__ == '__main__':
  137.     import time
  138.     print("ProgressBar and LoadingLabel example.")
  139.     print()
  140.     print()
  141.    
  142.     i = 0
  143.    
  144.     # Create a progress bar with custom message and fill character.
  145.     progress = ProgressBar("Downloading something", '=')
  146.     while i <= 100:
  147.         # In a while loop update the bar every 300 milliseconds.
  148.         # What ever you pass to the updateBar method is divided by 5 so
  149.         # it may never be larger then 100, at least untill I fix it :P
  150.         progress.updateBar(i)
  151.         i += 1
  152.         time.sleep(0.1)
  153.     progress.close()
  154.    
  155.     i = 0
  156.     # Pretty much the same structure for the LoadingLabel.
  157.     loadBar = LoadingLabel(("Loading", "Loading.", "Loading..", "Loading...", "Loading...."), "Complete!")
  158.     while i <= 20:
  159.         # Only difference here is that we don't have to pass an integer to the update method.
  160.         loadBar.update()
  161.         i += 1
  162.         time.sleep(0.4)
  163.     loadBar.close()
  164.  
Advertisement
Add Comment
Please, Sign In to add comment