ProgressMonitor   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 11
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 11
rs 10
wmc 3

3 Methods

Rating   Name   Duplication   Size   Complexity  
A show() 0 4 1
A done() 0 2 1
A __init__() 0 2 1
1
#!/usr/bin/env python
2
# coding=utf-8
3
"""
4
This example shows how to apply a filter function to the captured output
5
of a run. This is often useful when using progress bars or similar in the text
6
UI and you don't want to store formatting characters like backspaces and
7
linefeeds in the database.
8
"""
9
from __future__ import division, print_function, unicode_literals
10
11
import sys
12
import time
13
14
from sacred import Experiment
15
from sacred.utils import apply_backspaces_and_linefeeds
16
17
ex = Experiment('progress')
18
19
# try commenting out the line below to see the difference in captured output
20
ex.captured_out_filter = apply_backspaces_and_linefeeds
21
22
23
def write_and_flush(*args):
24
    for arg in args:
25
        sys.stdout.write(arg)
26
    sys.stdout.flush()
27
28
29
class ProgressMonitor(object):
30
    def __init__(self, count):
31
        self.count, self.progress = count, 0
32
33
    def show(self, n=1):
34
        self.progress += n
35
        text = 'Completed {}/{} tasks'.format(self.progress, self.count)
36
        write_and_flush('\b' * 80, '\r', text)
37
38
    def done(self):
39
        write_and_flush('\n')
40
41
42
def progress(items):
43
    p = ProgressMonitor(len(items))
44
    for item in items:
45
        yield item
46
        p.show()
47
    p.done()
48
49
50
@ex.main
51
def main():
52
    for item in progress(range(100)):
53
        time.sleep(0.05)
54
55
56
if __name__ == '__main__':
57
    run = ex.run_commandline()
58
    print('=' * 80)
59
    print('Captured output: ', repr(run.captured_out))
60