add testcode for iwlist
[dumbwifi.git] / output.py
blobd1fa040d1be8974106e7e727115d2ab37ec594fe
1 #!/usr/bin/env python
3 import os
4 import shutil
5 import sys
6 import time
8 from conf import config
11 class Logger:
13 def __init__(self):
14 self.dirty = False
15 self.pending = None
16 self.muted = False
18 # output: => Requesting ip...
19 def await(self, msg):
20 if self.pending:
21 raise Exception,\
22 "Attempted to display new pending message without closing previous"
24 msg = "=> %s..." % msg
25 self.pending = msg
26 self.dirty = False
27 print msg,
28 sys.stdout.flush()
29 self.log(msg)
31 # output: (=> Requesting ip...) done
32 def result(self, msg):
33 if not self.pending:
34 raise Exception,\
35 "Attempted to display result of action without pending message"
37 if not self.dirty:
38 print msg
39 self.log("%s %s" % (self.pending, msg))
40 else:
41 msg = "%s %s" % (self.pending, msg)
42 print "\r%s" % msg # workaround for space at the start of the line
43 self.log(msg)
44 self.pending = None
46 def display(self, msg):
47 if self.pending and not self.dirty:
48 self.dirty = True
49 msg = "\n%s" % msg
50 print msg
51 self.log(msg)
53 def err(self, msg, log=True):
54 msg = "Erratum: %s" % msg
55 if self.pending:
56 self.dirty = True
57 print >>sys.stderr, "\n%s" % msg
58 else: print >>sys.stderr, msg
59 if log: self.log(msg)
61 def log(self, msg):
62 if self.muted: return
63 try:
64 # truncate logfile
65 if os.path.isfile(config.logfile) and \
66 os.path.getsize(config.logfile) > config.logfile_size:
67 shutil.move(config.logfile, "%s.0" % config.logfile)
69 t = time.strftime("%d.%m.%y %H:%M:%S", time.gmtime())
71 f = open(config.logfile, 'a')
72 if msg[-1:] != '\n': msg += '\n'
73 f.write("[%s] %s" % (t, msg))
74 f.close()
75 except IOError:
76 self.err("Could not write to logfile %s" % config.logfile, log=False)
78 def mute(self, quiet=False):
79 if self.muted: return
80 if not quiet:
81 self.display("*** Halting output until we need to obtain ip again")
82 sys.stdin = open("/dev/null", 'r')
83 sys.stdout = open("/dev/null", 'w')
84 sys.stderr = open("/dev/null", 'w')
85 self.muted = True
87 def unmute(self, quiet=False):
88 if not self.muted: return
89 sys.stdin = sys.__stdin__
90 sys.stdout = sys.__stdout__
91 sys.stderr = sys.__stderr__
92 if not quiet: self.display("*** Resuming output")
93 self.muted = False
96 logger = Logger()