Marco Lui avatar Marco Lui committed cb0ef18

reorganized src to allow setup.py develop and setup.py install to work correctly

Comments (0)

Files changed (12)

src/__init__.py

-# -*- coding: utf-8 -*-
-# 
-#  __init__.py
-#  consoleLog
-#  
-#  Created by Lars Yencken on 2008-06-12.
-#  Copyright 2008-06-12 Lars Yencken. All rights reserved.
-# 
-
-__all__ = [
-        'consoleLog',
-        'io',
-        'progressBar',
-        'shell',
-        'slot',
-    ]
-
-#----------------------------------------------------------------------------#
-
-import consoleLog
-import progressBar
-from progressBar import withProgress
-import slot
-
-#----------------------------------------------------------------------------#
-
-# Provide a default logging object 
-default = consoleLog.ConsoleLogger()
-
-#----------------------------------------------------------------------------#
-
-def demo():
-    import time
-    sl = time.sleep
-    log = consoleLog.ConsoleLogger()
-
-    log.start('Starting logger demo')
-    log.log('Performing some initialisation')
-    sl(1.0)
-
-    log.start('Serious processing with substeps')
-    log.log('Substep 1')
-    sl(1.0)
-    log.log('Substep 2')
-    sl(1.0)
-    log.log('Substep 3 with progress ', newLine=False)
-    for i in withProgress(xrange(100)):
-        sl(0.1)
-    log.start('Substep 4 with slot', nSteps=1)
-    log.log('', newLine=False)
-    s = slot.Slot() 
-    for j in xrange(637):
-        time.sleep(0.01)
-        if j % 100 == 0:
-            s.update(str(j))
-    s.finish(str(j))
-    log.finish()
-
-    log.finish('Completed ok')
-
-    log.log('Postprocessing step')
-    sl(1.0)
-    log.finish()

src/consoleLog.py

-# -*- coding: utf-8 -*-
-# 
-#  consoleLog.py
-#  consoleLog
-#  
-#  Created by Lars Yencken on 2008-06-12.
-#  Copyright 2008 Lars Yencken. All rights reserved.
-# 
-
-"""
-A simple logging module which allows hierarchical logging without centralized
-control.
-
->>> log = ConsoleLogger()
->>> log.start('ABC', nSteps=3)
-ABC
->>> log.log('A')
-├─ A
->>> log.log('B')
-├─ B
->>> log.log('C')
-└─ C
->>> log.finish()
-"""
-
-#----------------------------------------------------------------------------#
-
-import sys
-import codecs
-
-_default_encoding = 'utf8'
-
-#----------------------------------------------------------------------------#
-
-class ConsoleLogger(object):
-    """
-    A console logging object, which can optionally be given an output stream
-    which it prints to, defaulting to stdout.
-    """
-    def __init__(self, output=None, trim=78, encoding=_default_encoding):
-        self.oStream = codecs.getwriter(encoding)(output or sys.stdout)
-        self.logStack = []
-        self.trim=trim
-
-    def start(self, message, nSteps=None):
-        """
-        Starts a new hierarchical logging section. Every call to start() must
-        be later matched by a call to finish().
-        """
-        self.log(message)
-        self.logStack.append(_SectionPadding(nSteps=nSteps))
-        return
-
-    def log(self, message, newLine=True):
-        """
-        Logs a message, with an optional newline. The most common case for
-        not using the newline is for subsequent use of a progress bar.
-        """
-        if self.logStack:
-            padding = []
-            for levelLogger in self.logStack[:-1]:
-                padding.append(levelLogger.getIntermediatePadding())
-            padding.append(self.logStack[-1].getCurrentPadding())
-        else:
-            padding = u''
-        oLine = u'%s%s' % (u''.join(padding), message)
-        if self.trim and len(oLine) > self.trim:
-            oLine = oLine[:self.trim - 3] + u'...'
-        self.oStream.write(oLine)
-        if newLine:
-            print >> self.oStream
-        else:
-            self.oStream.flush()
-        return
-
-    def space(self):
-        if self.logStack:
-            padding = []
-            for levelLogger in self.logStack:
-                padding.append(levelLogger.getIntermediatePadding())
-            padding = u''.join(padding)
-        else:
-            padding = u''
-        print >> self.oStream, padding
-        return
-
-    def finish(self, message="Done"):
-        """
-        Ends a hierarchical logging section which was previously created using
-        start().
-        """
-        padding = []
-        for levelLogger in self.logStack[:-1]:
-            padding.append(levelLogger.getIntermediatePadding())
-        last = self.logStack.pop()
-        padding.append(last.getLastPadding())
-        if last.needsFinish():
-            print >> self.oStream, u"%s%s" % (u''.join(padding), message)
-        return
-
-#----------------------------------------------------------------------------#
-
-class _SectionPadding(object):
-    """
-    A manager for the amount of padding needed for any given log line, as well
-    as any embellishments needed to indicate hierarchy.
-    """
-    def __init__(self, nSteps=None):
-        """Private constructor used internally."""
-        self.nSteps = nSteps
-        self.currentStep = 0
-
-    def getIntermediatePadding(self):
-        if self.currentStep == self.nSteps:
-            return u'   '
-        else:
-            return u'│  '
-
-    def getCurrentPadding(self):
-        self.currentStep += 1
-        if self.currentStep == self.nSteps:
-            return u'└─ '
-        else:
-            return u'├─ '
-
-    def needsFinish(self):
-        return self.currentStep != self.nSteps
-
-    def getLastPadding(self):
-        return u'└─ '
-
-#----------------------------------------------------------------------------#

src/consoleLog/__init__.py

+# -*- coding: utf-8 -*-
+# 
+#  __init__.py
+#  consoleLog
+#  
+#  Created by Lars Yencken on 2008-06-12.
+#  Copyright 2008-06-12 Lars Yencken. All rights reserved.
+# 
+
+__all__ = [
+        'consoleLog',
+        'io',
+        'progressBar',
+        'shell',
+        'slot',
+    ]
+
+#----------------------------------------------------------------------------#
+
+import consoleLog
+import progressBar
+from progressBar import withProgress
+import slot
+
+#----------------------------------------------------------------------------#
+
+# Provide a default logging object 
+default = consoleLog.ConsoleLogger()
+
+#----------------------------------------------------------------------------#
+
+def demo():
+    import time
+    sl = time.sleep
+    log = consoleLog.ConsoleLogger()
+
+    log.start('Starting logger demo')
+    log.log('Performing some initialisation')
+    sl(1.0)
+
+    log.start('Serious processing with substeps')
+    log.log('Substep 1')
+    sl(1.0)
+    log.log('Substep 2')
+    sl(1.0)
+    log.log('Substep 3 with progress ', newLine=False)
+    for i in withProgress(xrange(100)):
+        sl(0.1)
+    log.start('Substep 4 with slot', nSteps=1)
+    log.log('', newLine=False)
+    s = slot.Slot() 
+    for j in xrange(637):
+        time.sleep(0.01)
+        if j % 100 == 0:
+            s.update(str(j))
+    s.finish(str(j))
+    log.finish()
+
+    log.finish('Completed ok')
+
+    log.log('Postprocessing step')
+    sl(1.0)
+    log.finish()

src/consoleLog/consoleLog.py

+# -*- coding: utf-8 -*-
+# 
+#  consoleLog.py
+#  consoleLog
+#  
+#  Created by Lars Yencken on 2008-06-12.
+#  Copyright 2008 Lars Yencken. All rights reserved.
+# 
+
+"""
+A simple logging module which allows hierarchical logging without centralized
+control.
+
+>>> log = ConsoleLogger()
+>>> log.start('ABC', nSteps=3)
+ABC
+>>> log.log('A')
+├─ A
+>>> log.log('B')
+├─ B
+>>> log.log('C')
+└─ C
+>>> log.finish()
+"""
+
+#----------------------------------------------------------------------------#
+
+import sys
+import codecs
+
+_default_encoding = 'utf8'
+
+#----------------------------------------------------------------------------#
+
+class ConsoleLogger(object):
+    """
+    A console logging object, which can optionally be given an output stream
+    which it prints to, defaulting to stdout.
+    """
+    def __init__(self, output=None, trim=78, encoding=_default_encoding):
+        self.oStream = codecs.getwriter(encoding)(output or sys.stdout)
+        self.logStack = []
+        self.trim=trim
+
+    def start(self, message, nSteps=None):
+        """
+        Starts a new hierarchical logging section. Every call to start() must
+        be later matched by a call to finish().
+        """
+        self.log(message)
+        self.logStack.append(_SectionPadding(nSteps=nSteps))
+        return
+
+    def log(self, message, newLine=True):
+        """
+        Logs a message, with an optional newline. The most common case for
+        not using the newline is for subsequent use of a progress bar.
+        """
+        if self.logStack:
+            padding = []
+            for levelLogger in self.logStack[:-1]:
+                padding.append(levelLogger.getIntermediatePadding())
+            padding.append(self.logStack[-1].getCurrentPadding())
+        else:
+            padding = u''
+        oLine = u'%s%s' % (u''.join(padding), message)
+        if self.trim and len(oLine) > self.trim:
+            oLine = oLine[:self.trim - 3] + u'...'
+        self.oStream.write(oLine)
+        if newLine:
+            print >> self.oStream
+        else:
+            self.oStream.flush()
+        return
+
+    def space(self):
+        if self.logStack:
+            padding = []
+            for levelLogger in self.logStack:
+                padding.append(levelLogger.getIntermediatePadding())
+            padding = u''.join(padding)
+        else:
+            padding = u''
+        print >> self.oStream, padding
+        return
+
+    def finish(self, message="Done"):
+        """
+        Ends a hierarchical logging section which was previously created using
+        start().
+        """
+        padding = []
+        for levelLogger in self.logStack[:-1]:
+            padding.append(levelLogger.getIntermediatePadding())
+        last = self.logStack.pop()
+        padding.append(last.getLastPadding())
+        if last.needsFinish():
+            print >> self.oStream, u"%s%s" % (u''.join(padding), message)
+        return
+
+#----------------------------------------------------------------------------#
+
+class _SectionPadding(object):
+    """
+    A manager for the amount of padding needed for any given log line, as well
+    as any embellishments needed to indicate hierarchy.
+    """
+    def __init__(self, nSteps=None):
+        """Private constructor used internally."""
+        self.nSteps = nSteps
+        self.currentStep = 0
+
+    def getIntermediatePadding(self):
+        if self.currentStep == self.nSteps:
+            return u'   '
+        else:
+            return u'│  '
+
+    def getCurrentPadding(self):
+        self.currentStep += 1
+        if self.currentStep == self.nSteps:
+            return u'└─ '
+        else:
+            return u'├─ '
+
+    def needsFinish(self):
+        return self.currentStep != self.nSteps
+
+    def getLastPadding(self):
+        return u'└─ '
+
+#----------------------------------------------------------------------------#

src/consoleLog/io.py

+# -*- coding: utf-8 -*-
+# 
+#  io.py
+#  consoleLog
+#  
+#  Created by Lars Yencken on 2008-06-12.
+#  Copyright 2008-06-12 Lars Yencken. All rights reserved.
+# 
+
+"""
+The sopen() convenience method for file handles.
+"""
+
+import sys
+import codecs
+import bz2, gzip
+
+def sopen(filename, mode='rb', encoding='utf8'):
+    """
+    Transparently uses compression on the given file based on file
+    extension.
+
+    @param filename: The filename to use for the file handle.
+    @param mode: The mode to open the file in, e.g. 'r' for read, 'w' for
+        write, 'a' for append.
+    @param encoding: The encoding to use. Can be set to None to avoid
+        using unicode at all.
+    """
+    readMode = 'r' in mode
+    if readMode and 'w' in mode:
+        raise Exception, "Must be either read mode or write, but not both"
+
+    if filename.endswith('.bz2'):
+        stream = bz2.BZ2File(filename, mode)
+    elif filename.endswith('.gz'):
+        stream = gzip.GzipFile(filename, mode)
+    elif filename == '-':
+        if readMode:
+            stream = sys.stdin
+        else:
+            stream = sys.stdout
+    else:
+        stream = open(filename, mode)
+    
+    if encoding not in (None, 'byte'):
+        if readMode:
+            return codecs.getreader(encoding)(stream)
+        else:
+            return codecs.getwriter(encoding)(stream)
+    
+    return stream

src/consoleLog/progressBar.py

+# -*- coding: utf-8 -*-
+# 
+#  progressBar.py
+#  consoleLog
+#  
+#  Created by Lars Yencken on 2008-06-12.
+#  Copyright 2008-06-12 Lars Yencken. All rights reserved.
+#
+
+"""
+A simple console progress bar, with support for iterator wrapping.
+"""
+
+#----------------------------------------------------------------------------#
+
+import sys
+import time
+
+import io
+import shellColor
+import slot
+
+#----------------------------------------------------------------------------#
+
+_currentBar = None
+
+class IllegalNestingError(Exception):
+    pass
+
+def withProgress(seq, modValue=1, size=None, force=False):
+    """
+    A wrapper for sequence which adds a progress bar.
+    """
+    global _currentBar
+    if _currentBar:
+        raise IllegalNestingError("can't nest progress bars")
+
+    progress = ProgressBar()
+    if size is None:
+        if hasattr(seq, '__len__'):
+            progress.start(len(seq))
+        elif force:
+            seq = list(seq)
+            progress.start(len(seq))
+        else:
+            raise ValueError, "seq has no __len__ method"
+    else:
+        progress.start(size)
+
+    _currentBar = progress
+
+    count = 0
+    for item in seq:
+        yield item
+        count += 1
+        if count % modValue == 0:
+            progress.update(count)
+
+    progress.finish()
+
+    _currentBar = None
+    return
+
+#----------------------------------------------------------------------------#
+
+def tick():
+    """
+    Indicate activity in the current progress bar.
+    """
+    global _currentBar
+
+    if _currentBar is not None:
+        _currentBar.tick()
+    return
+
+#----------------------------------------------------------------------------#
+
+class ProgressBar:
+    "A progress bar which gets printed to stdout."
+    def __init__(self, stringSize=20):
+        "Creates a new instance, setting the size as needed."
+        self._slot = slot.Slot()
+        self._stringSize = stringSize
+        self._count = 0
+        self._totalCount = None
+        self._lastRotation = 0
+        self._startTime = None
+
+        self._rotation = ['/', '-', '\\', '|']
+        self._numRotations = len(self._rotation)
+
+        return
+
+    def reset(self):
+        "Resets the progress bar to initial conditions."
+        self._count = 0
+        self._totalCount = None
+        self._lastLineSize = None
+        self._lastRotation = 0
+        self._startTime = None
+
+        return
+    
+    def start(self, totalCount):
+        """
+        Starts the progress bar. This will be the first output from the
+        bar. At this stage it needs the total count so that it can
+        calculate percentages.
+
+        @param totalCount: The count which represents 'finished'.
+        """
+        assert self._count == 0, "Progress bar already started, call reset()"
+        assert totalCount > 0, "Progress bar needs a non-zero total count"
+        self._totalCount = totalCount
+        progressLine = '[' + shellColor.color('/', 'red') + \
+                (self._stringSize-1)*' ' + ']   0%'
+        self._slot.update(progressLine)
+        self._startTime = time.time()
+
+    def update(self, count):
+        """
+        Updates the progress bar with the current count. This is useful
+        to call even if the count has not increased, since it provides
+        visual feedback to the user that the process is active.
+
+        @param count: The current count
+        """
+        count = int(count)
+        self._count = count
+        if count < 0 or count > self._totalCount:
+            raise Exception, 'Bad count for progress bar'
+
+        n = (count * self._stringSize) / self._totalCount
+        percent = (100*count) / self._totalCount
+        m = self._stringSize - n - 1 # subtract one for the rotating char
+
+        self._lastRotation = (self._lastRotation + 1) % self._numRotations
+        if percent < 100:
+            rotChar = self._rotation[self._lastRotation]
+        else:
+            rotChar = ''
+
+        progressLine = '[' + shellColor.color(n*'-' + rotChar, 'red') + \
+                m*' ' + '] ' + str('%3d%%' % percent)
+        self._slot.update(progressLine)
+
+    def tick(self):
+        "Perform a quick update."
+        self.update(self._count)
+
+    def fractional(self, fraction):
+        "Set a fractional percentage completion, e.g. 0.3333 -> 33%."
+        assert fraction >= 0 and fraction <= 1
+        self.update(int(fraction * self._totalCount))
+    
+    def finish(self):
+        "Fixes to 100% complete, and writes the time taken."
+        assert self._totalCount > 0, "Progress bar wasn't initialised"
+        self.update(self._totalCount)
+
+        timeTaken = int(time.time() - self._startTime)
+        (mins, secs) = divmod(timeTaken, 60)
+        if not mins:
+            timeString = ' (%ds)' % secs
+        else:
+            (hours, mins) = divmod(mins, 60)
+            if not hours:
+                timeString = ' (%dm %ds)' % (mins, secs)
+            else:
+                timeString = ' (%dh %dm %ds)' % (hours, mins, secs)
+
+        print >> sys.stdout, timeString
+
+#----------------------------------------------------------------------------#
+
+if __name__ == '__main__':
+    for i in withProgress(range(100)):
+        time.sleep(0.1)

src/consoleLog/shellColor.py

+# -*- coding: utf-8 -*-
+#----------------------------------------------------------------------------#
+# shellColor.py
+# vim: ts=4 sw=4 sts=4 et tw=78:
+# Tue May  2 11:36:56 2006
+#
+#----------------------------------------------------------------------------#
+
+"""
+Colored output for unix shells, which can be disabled to avoid problems on
+non-supporting platforms.
+"""
+
+#----------------------------------------------------------------------------#
+
+# whether color output is currently enabled or not
+_enableColor = True
+
+#----------------------------------------------------------------------------#
+
+def enableColor():
+    """Enable colorized output from this module's methods."""
+    global _enableColor
+    _enableColor = True
+    return
+
+#----------------------------------------------------------------------------#
+
+def disableColor():
+    """Disable colorized output from this module's methods."""
+    global _enableColor
+    _enableColor = False
+    return
+
+#----------------------------------------------------------------------------#
+
+_colString = '\x1b[01;%.2dm'
+_resetString = '\x1b[01;00m'
+
+_colors = {
+    'regular':      0,
+    'darkgrey':     30,
+    'red':          31,
+    'lightgreen':   32,
+    'yellow':       33,
+    'blue':         34
+}
+
+#----------------------------------------------------------------------------#
+
+def color(strObj, color):
+    """
+    Changes the color of the given string as printed on a UNIX shell.
+
+    >>> color('dog', 'blue') == '\x1b[01;34mdog\x1b[01;00m'
+    True
+    """ 
+    code = _colors.get(color)
+    if code is None:
+        raise KeyError('no color matches name: %s' % color)
+
+    global _enableColor
+    if _enableColor:
+        return (_colString % _colors[color]) + strObj + (_colString % 0)
+    else:
+        return strObj
+
+#----------------------------------------------------------------------------#
+
+def changeColor(color):
+    """ Change the color for the remaining text after this is printed to the
+        given color.
+    """
+    global _enableColor
+    if _enableColor:
+        return _colString % colors[color]
+    else:
+        return ''
+
+#----------------------------------------------------------------------------#
+
+def realLen(strObj):
+    """
+    Determine the real length of a string object.
+
+    >>> realLen('dog gone')
+    8
+    >>> realLen(color('dog', 'blue') + ' gone')
+    8
+    >>> realLen('\x1b[01;34mdog\x1b[01;00m gone')
+    8
+    """
+    finalLen = 0
+    startIndex = 0
+
+    colorStr = '\x1b[01;'
+
+    nextColor = strObj.find(colorStr, startIndex)
+    while nextColor != -1:
+        finalLen += nextColor - startIndex
+        startIndex = nextColor + len(_resetString)
+        nextColor = strObj.find(colorStr, startIndex)
+
+    finalLen += len(strObj) - startIndex
+
+    return finalLen
+
+#----------------------------------------------------------------------------#
+
+def resetColor():
+    """
+    Return the string to print to reset the color to the default.
+    """
+    global _enableColor
+
+    if _enableColor:
+        return _resetString
+
+    return ''
+
+#----------------------------------------------------------------------------#

src/consoleLog/slot.py

+# -*- coding: utf-8 -*-
+#
+#  slot.py
+#  consoleLog
+# 
+#  Created by Lars Yencken on 03-05-2010.
+#  Copyright 2010 Lars Yencken. All rights reserved.
+#
+
+"""
+"""
+
+import sys
+
+import shellColor
+
+class Slot(object):
+    """
+    A generic text slot which can be overwritten repeatedly.
+    """
+    def __init__(self, text=u'', stream=sys.stdout):
+        if u'\n' in text:
+            raise Exception('slots cannot undo newlines')
+        self.stream = stream
+        self.last_text = None
+        self.is_finished = False
+        if text:
+            self.update(text)
+
+    def update(self, text):
+        if self.is_finished:
+            raise Exception("slot already finalized, cannot update it")
+
+        if isinstance(text, unicode):
+            text = text.encode('utf8')
+
+        if self.last_text:
+            last_len = shellColor.realLen(self.last_text)
+            self.stream.write('\b' * shellColor.realLen(self.last_text))
+            this_len = shellColor.realLen(text)
+            if this_len < last_len:
+                text = text + ' ' * (last_len - this_len)
+
+        self.stream.write(text)
+        self.stream.flush()
+        self.last_text = text
+
+    def finish(self, text=None):
+        if text:
+            self.update(text)
+        print >> self.stream
+        self.is_finished = True
+
+# vim: ts=4 sw=4 sts=4 et tw=78:

src/io.py

-# -*- coding: utf-8 -*-
-# 
-#  io.py
-#  consoleLog
-#  
-#  Created by Lars Yencken on 2008-06-12.
-#  Copyright 2008-06-12 Lars Yencken. All rights reserved.
-# 
-
-"""
-The sopen() convenience method for file handles.
-"""
-
-import sys
-import codecs
-import bz2, gzip
-
-def sopen(filename, mode='rb', encoding='utf8'):
-    """
-    Transparently uses compression on the given file based on file
-    extension.
-
-    @param filename: The filename to use for the file handle.
-    @param mode: The mode to open the file in, e.g. 'r' for read, 'w' for
-        write, 'a' for append.
-    @param encoding: The encoding to use. Can be set to None to avoid
-        using unicode at all.
-    """
-    readMode = 'r' in mode
-    if readMode and 'w' in mode:
-        raise Exception, "Must be either read mode or write, but not both"
-
-    if filename.endswith('.bz2'):
-        stream = bz2.BZ2File(filename, mode)
-    elif filename.endswith('.gz'):
-        stream = gzip.GzipFile(filename, mode)
-    elif filename == '-':
-        if readMode:
-            stream = sys.stdin
-        else:
-            stream = sys.stdout
-    else:
-        stream = open(filename, mode)
-    
-    if encoding not in (None, 'byte'):
-        if readMode:
-            return codecs.getreader(encoding)(stream)
-        else:
-            return codecs.getwriter(encoding)(stream)
-    
-    return stream

src/progressBar.py

-# -*- coding: utf-8 -*-
-# 
-#  progressBar.py
-#  consoleLog
-#  
-#  Created by Lars Yencken on 2008-06-12.
-#  Copyright 2008-06-12 Lars Yencken. All rights reserved.
-#
-
-"""
-A simple console progress bar, with support for iterator wrapping.
-"""
-
-#----------------------------------------------------------------------------#
-
-import sys
-import time
-
-import io
-import shellColor
-import slot
-
-#----------------------------------------------------------------------------#
-
-_currentBar = None
-
-class IllegalNestingError(Exception):
-    pass
-
-def withProgress(seq, modValue=1, size=None, force=False):
-    """
-    A wrapper for sequence which adds a progress bar.
-    """
-    global _currentBar
-    if _currentBar:
-        raise IllegalNestingError("can't nest progress bars")
-
-    progress = ProgressBar()
-    if size is None:
-        if hasattr(seq, '__len__'):
-            progress.start(len(seq))
-        elif force:
-            seq = list(seq)
-            progress.start(len(seq))
-        else:
-            raise ValueError, "seq has no __len__ method"
-    else:
-        progress.start(size)
-
-    _currentBar = progress
-
-    count = 0
-    for item in seq:
-        yield item
-        count += 1
-        if count % modValue == 0:
-            progress.update(count)
-
-    progress.finish()
-
-    _currentBar = None
-    return
-
-#----------------------------------------------------------------------------#
-
-def tick():
-    """
-    Indicate activity in the current progress bar.
-    """
-    global _currentBar
-
-    if _currentBar is not None:
-        _currentBar.tick()
-    return
-
-#----------------------------------------------------------------------------#
-
-class ProgressBar:
-    "A progress bar which gets printed to stdout."
-    def __init__(self, stringSize=20):
-        "Creates a new instance, setting the size as needed."
-        self._slot = slot.Slot()
-        self._stringSize = stringSize
-        self._count = 0
-        self._totalCount = None
-        self._lastRotation = 0
-        self._startTime = None
-
-        self._rotation = ['/', '-', '\\', '|']
-        self._numRotations = len(self._rotation)
-
-        return
-
-    def reset(self):
-        "Resets the progress bar to initial conditions."
-        self._count = 0
-        self._totalCount = None
-        self._lastLineSize = None
-        self._lastRotation = 0
-        self._startTime = None
-
-        return
-    
-    def start(self, totalCount):
-        """
-        Starts the progress bar. This will be the first output from the
-        bar. At this stage it needs the total count so that it can
-        calculate percentages.
-
-        @param totalCount: The count which represents 'finished'.
-        """
-        assert self._count == 0, "Progress bar already started, call reset()"
-        assert totalCount > 0, "Progress bar needs a non-zero total count"
-        self._totalCount = totalCount
-        progressLine = '[' + shellColor.color('/', 'red') + \
-                (self._stringSize-1)*' ' + ']   0%'
-        self._slot.update(progressLine)
-        self._startTime = time.time()
-
-    def update(self, count):
-        """
-        Updates the progress bar with the current count. This is useful
-        to call even if the count has not increased, since it provides
-        visual feedback to the user that the process is active.
-
-        @param count: The current count
-        """
-        count = int(count)
-        self._count = count
-        if count < 0 or count > self._totalCount:
-            raise Exception, 'Bad count for progress bar'
-
-        n = (count * self._stringSize) / self._totalCount
-        percent = (100*count) / self._totalCount
-        m = self._stringSize - n - 1 # subtract one for the rotating char
-
-        self._lastRotation = (self._lastRotation + 1) % self._numRotations
-        if percent < 100:
-            rotChar = self._rotation[self._lastRotation]
-        else:
-            rotChar = ''
-
-        progressLine = '[' + shellColor.color(n*'-' + rotChar, 'red') + \
-                m*' ' + '] ' + str('%3d%%' % percent)
-        self._slot.update(progressLine)
-
-    def tick(self):
-        "Perform a quick update."
-        self.update(self._count)
-
-    def fractional(self, fraction):
-        "Set a fractional percentage completion, e.g. 0.3333 -> 33%."
-        assert fraction >= 0 and fraction <= 1
-        self.update(int(fraction * self._totalCount))
-    
-    def finish(self):
-        "Fixes to 100% complete, and writes the time taken."
-        assert self._totalCount > 0, "Progress bar wasn't initialised"
-        self.update(self._totalCount)
-
-        timeTaken = int(time.time() - self._startTime)
-        (mins, secs) = divmod(timeTaken, 60)
-        if not mins:
-            timeString = ' (%ds)' % secs
-        else:
-            (hours, mins) = divmod(mins, 60)
-            if not hours:
-                timeString = ' (%dm %ds)' % (mins, secs)
-            else:
-                timeString = ' (%dh %dm %ds)' % (hours, mins, secs)
-
-        print >> sys.stdout, timeString
-
-#----------------------------------------------------------------------------#
-
-if __name__ == '__main__':
-    for i in withProgress(range(100)):
-        time.sleep(0.1)

src/shellColor.py

-# -*- coding: utf-8 -*-
-#----------------------------------------------------------------------------#
-# shellColor.py
-# vim: ts=4 sw=4 sts=4 et tw=78:
-# Tue May  2 11:36:56 2006
-#
-#----------------------------------------------------------------------------#
-
-"""
-Colored output for unix shells, which can be disabled to avoid problems on
-non-supporting platforms.
-"""
-
-#----------------------------------------------------------------------------#
-
-# whether color output is currently enabled or not
-_enableColor = True
-
-#----------------------------------------------------------------------------#
-
-def enableColor():
-    """Enable colorized output from this module's methods."""
-    global _enableColor
-    _enableColor = True
-    return
-
-#----------------------------------------------------------------------------#
-
-def disableColor():
-    """Disable colorized output from this module's methods."""
-    global _enableColor
-    _enableColor = False
-    return
-
-#----------------------------------------------------------------------------#
-
-_colString = '\x1b[01;%.2dm'
-_resetString = '\x1b[01;00m'
-
-_colors = {
-    'regular':      0,
-    'darkgrey':     30,
-    'red':          31,
-    'lightgreen':   32,
-    'yellow':       33,
-    'blue':         34
-}
-
-#----------------------------------------------------------------------------#
-
-def color(strObj, color):
-    """
-    Changes the color of the given string as printed on a UNIX shell.
-
-    >>> color('dog', 'blue') == '\x1b[01;34mdog\x1b[01;00m'
-    True
-    """ 
-    code = _colors.get(color)
-    if code is None:
-        raise KeyError('no color matches name: %s' % color)
-
-    global _enableColor
-    if _enableColor:
-        return (_colString % _colors[color]) + strObj + (_colString % 0)
-    else:
-        return strObj
-
-#----------------------------------------------------------------------------#
-
-def changeColor(color):
-    """ Change the color for the remaining text after this is printed to the
-        given color.
-    """
-    global _enableColor
-    if _enableColor:
-        return _colString % colors[color]
-    else:
-        return ''
-
-#----------------------------------------------------------------------------#
-
-def realLen(strObj):
-    """
-    Determine the real length of a string object.
-
-    >>> realLen('dog gone')
-    8
-    >>> realLen(color('dog', 'blue') + ' gone')
-    8
-    >>> realLen('\x1b[01;34mdog\x1b[01;00m gone')
-    8
-    """
-    finalLen = 0
-    startIndex = 0
-
-    colorStr = '\x1b[01;'
-
-    nextColor = strObj.find(colorStr, startIndex)
-    while nextColor != -1:
-        finalLen += nextColor - startIndex
-        startIndex = nextColor + len(_resetString)
-        nextColor = strObj.find(colorStr, startIndex)
-
-    finalLen += len(strObj) - startIndex
-
-    return finalLen
-
-#----------------------------------------------------------------------------#
-
-def resetColor():
-    """
-    Return the string to print to reset the color to the default.
-    """
-    global _enableColor
-
-    if _enableColor:
-        return _resetString
-
-    return ''
-
-#----------------------------------------------------------------------------#

src/slot.py

-# -*- coding: utf-8 -*-
-#
-#  slot.py
-#  consoleLog
-# 
-#  Created by Lars Yencken on 03-05-2010.
-#  Copyright 2010 Lars Yencken. All rights reserved.
-#
-
-"""
-"""
-
-import sys
-
-import shellColor
-
-class Slot(object):
-    """
-    A generic text slot which can be overwritten repeatedly.
-    """
-    def __init__(self, text=u'', stream=sys.stdout):
-        if u'\n' in text:
-            raise Exception('slots cannot undo newlines')
-        self.stream = stream
-        self.last_text = None
-        self.is_finished = False
-        if text:
-            self.update(text)
-
-    def update(self, text):
-        if self.is_finished:
-            raise Exception("slot already finalized, cannot update it")
-
-        if isinstance(text, unicode):
-            text = text.encode('utf8')
-
-        if self.last_text:
-            last_len = shellColor.realLen(self.last_text)
-            self.stream.write('\b' * shellColor.realLen(self.last_text))
-            this_len = shellColor.realLen(text)
-            if this_len < last_len:
-                text = text + ' ' * (last_len - this_len)
-
-        self.stream.write(text)
-        self.stream.flush()
-        self.last_text = text
-
-    def finish(self, text=None):
-        if text:
-            self.update(text)
-        print >> self.stream
-        self.is_finished = True
-
-# vim: ts=4 sw=4 sts=4 et tw=78:
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.