summaryrefslogtreecommitdiffstats
path: root/askbot/utils/console.py
blob: fe6ad29e5752777dc108f67781d4e7f103074413 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
"""functions that directly handle user input
"""
import sys
import time
from askbot.utils import path

def choice_dialog(prompt_phrase, choices = None, invalid_phrase = None):
    """prints a prompt, accepts keyboard input
    and makes sure that user response is one of given
    in the choices argument, which is required
    and must be a list

    invalid_phrase must be a string with %(opt_string)s
    placeholder
    """
    assert(hasattr(choices, '__iter__'))
    assert(not isinstance(choices, basestring))
    while 1:
        response = raw_input('\n%s (type %s): ' % (prompt_phrase, '/'.join(choices)))
        if response in choices:
            return response
        elif invalid_phrase != None:
            opt_string = ','.join(choices)
            print invalid_phrase % {'opt_string': opt_string}
        time.sleep(1)

def open_new_file(prompt_phrase, extension = '', hint = None):
    """will ask for a file name to be typed
    by user into the console path to the file can be
    either relative or absolute. Extension will be appended
    to the given file name.
    Return value is the file object.
    """
    if extension != '':
        if extension[0] != '.':
            extension = '.' + extension
    else:
        extension = ''

    file_object = None
    if hint:
        file_path = path.extend_file_name(hint, extension)
        file_object = path.create_file_if_does_not_exist(file_path, print_warning = True)
        
    while file_object == None:
        file_path = raw_input(prompt_phrase)
        file_path = path.extend_file_name(file_path, extension)
        file_object = path.create_file_if_does_not_exist(file_path, print_warning = True)

    return file_object

def print_action(action_text, nowipe = False):
    """print the string to the standard output
    then wipe it out to clear space
    """
    #for some reason sys.stdout.write does not work here
    #when action text is unicode
    print action_text,
    sys.stdout.flush()
    if nowipe == False:
        #return to the beginning of the word
        sys.stdout.write('\b' * len(action_text))
        #white out the printed text
        sys.stdout.write(' ' * len(action_text))
        #return again
        sys.stdout.write('\b' * len(action_text))
    else:
        sys.stdout.write('\n')

def print_progress(elapsed, total, nowipe = False):
    """print dynamic output of progress of some
    operation, in percent, to the console and clear the output with
    a backspace character to have the number increment
    in-place"""
    output = '%6.2f%%' % (100 * float(elapsed)/float(total))
    print_action(output, nowipe)

class ProgressBar(object):
    """A wrapper for an iterator, that prints 
    a progress bar along the way of iteration
    """
    def __init__(self, iterable, length, message = ''):
        self.iterable = iterable
        self.length = length
        self.counter = float(0)
        self.barlen = 60
        self.progress = ''
        if message and length > 0:
            print message
 

    def __iter__(self):
        return self

    def next(self):

        try:
            result = self.iterable.next()
        except StopIteration:
            if self.length > 0:
                sys.stdout.write('\n')
            raise

        sys.stdout.write('\b'*len(self.progress))

        if self.length < self.barlen:
            sys.stdout.write('-'*(self.barlen/self.length))
        elif int(self.counter) % (self.length / self.barlen) == 0:
            sys.stdout.write('-')

        self.progress = ' %.2f%%' % (100 * (self.counter/self.length))
        sys.stdout.write(self.progress)
        sys.stdout.flush()

        self.counter += 1
        return result