update
[dumbwifi.git] / output.py
blob7d0cddef177d443a94ae2075b2b97f954646e433
1 #!/usr/bin/env python
3 # Author: Martin Matusiak <numerodix@gmail.com>
4 # Licensed under the GNU Public License, version 3.
6 import os
7 import shutil
8 import sys
9 import time
11 from conf import config
14 class Logger:
16 def __init__(self):
17 self.dirty = False
18 self.pending = None
19 self.muted = False
21 # output: => Requesting ip...
22 def await(self, msg):
23 if self.pending:
24 raise Exception,\
25 "Attempted to display new pending message without closing previous"
27 msg = "=> %s..." % msg
28 self.pending = msg
29 self.dirty = False
30 print msg,
31 self.log(msg)
32 sys.stdout.flush()
34 # output: (=> Requesting ip...) done
35 def result(self, msg):
36 if not self.pending:
37 raise Exception,\
38 "Attempted to display result of action without pending message"
40 if not self.dirty:
41 print msg
42 self.log("%s %s" % (self.pending, msg))
43 else:
44 msg = "%s %s" % (self.pending, msg)
45 print "\r%s" % msg # workaround for space at the start of the line
46 self.log(msg)
47 self.pending = None
48 sys.stdout.flush()
50 def display(self, msg, log=True):
51 if self.pending and not self.dirty:
52 self.dirty = True
53 msg = "\n%s" % msg
54 print msg
55 if log: self.log(msg)
56 sys.stdout.flush()
58 def err(self, msg, log=True):
59 msg = "Erratum: %s" % msg
60 if self.pending:
61 self.dirty = True
62 print >>sys.stderr, "\n%s" % msg
63 else: print >>sys.stderr, msg
64 if log: self.log(msg)
65 sys.stdout.flush()
67 def log(self, msg):
68 if self.muted: return
69 try:
70 # truncate logfile
71 if os.path.isfile(config.logfile) and \
72 os.path.getsize(config.logfile) > config.logfile_size:
73 shutil.move(config.logfile, "%s.0" % config.logfile)
75 t = time.strftime("%d.%m.%y %H:%M:%S", time.gmtime())
77 f = open(config.logfile, 'a')
78 if msg[-1:] != '\n': msg += '\n'
79 f.write("[%s] %s" % (t, msg))
80 f.close()
81 except IOError:
82 self.err("Could not write to logfile %s" % config.logfile, log=False)
84 def mute(self, quiet=False):
85 if self.muted: return
86 if not quiet:
87 self.display("*** Halting output until we need to obtain ip again")
88 sys.stdin = open("/dev/null", 'r')
89 sys.stdout = open("/dev/null", 'w')
90 sys.stderr = open("/dev/null", 'w')
91 self.muted = True
93 def unmute(self, quiet=False):
94 if not self.muted: return
95 sys.stdin = sys.__stdin__
96 sys.stdout = sys.__stdout__
97 sys.stderr = sys.__stderr__
98 if not quiet: self.display("*** Resuming output")
99 self.muted = False
102 logger = Logger()