4 # Copyright (C) 2010 Saúl ibarra Corretgé <saghul@gmail.com>
8 pydmesg: dmesg with human-readable timestamps
11 from __future__ import with_statement
17 from datetime import datetime, timedelta
20 _datetime_format = "%Y-%m-%d %H:%M:%S"
21 _dmesg_line_regex = re.compile("^\[(?P<time>\d+\.\d+)\](?P<line>.*)$")
23 def exec_process(cmdline, silent, input=None, **kwargs):
24 """Execute a subprocess and returns the returncode, stdout buffer and stderr buffer.
25 Optionally prints stdout and stderr while running."""
27 sub = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
28 stdout, stderr = sub.communicate(input=input)
29 returncode = sub.returncode
31 sys.stdout.write(stdout)
32 sys.stderr.write(stderr)
35 raise RuntimeError('"%s" is not present on this system' % cmdline[0])
39 raise RuntimeError('Got return value %d while executing "%s", stderr output was:\n%s' % (returncode, " ".join(cmdline), stderr.rstrip("\n")))
46 with open('/proc/uptime') as f:
47 uptime_diff = f.read().strip().split()[0]
52 uptime = now - timedelta(seconds=int(uptime_diff.split('.')[0]), microseconds=int(uptime_diff.split('.')[1]))
56 dmesg_data = exec_process(['dmesg'], True)
57 for line in dmesg_data.split('\n'):
60 match = _dmesg_line_regex.match(line)
63 seconds = int(match.groupdict().get('time', '').split('.')[0])
64 nanoseconds = int(match.groupdict().get('time', '').split('.')[1])
65 microseconds = int(round(nanoseconds * 0.001))
66 line = match.groupdict().get('line', '')
67 t = uptime + timedelta(seconds=seconds, microseconds=microseconds)
71 print "[%s]%s" % (t.strftime(_datetime_format), line)
74 if __name__ == '__main__':