pydmesg 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #!/usr/bin/env python
  2. # coding=utf8
  3. # Copyright (C) 2010 Saúl ibarra Corretgé <saghul@gmail.com>
  4. #
  5. """
  6. pydmesg: dmesg with human-readable timestamps
  7. """
  8. from __future__ import with_statement
  9. import re
  10. import subprocess
  11. import sys
  12. from datetime import datetime, timedelta
  13. _datetime_format = "%Y-%m-%d %H:%M:%S"
  14. _dmesg_line_regex = re.compile("^\[(?P<time>\d+\.\d+)\](?P<line>.*)$")
  15. def exec_process(cmdline, silent, input=None, **kwargs):
  16. """Execute a subprocess and returns the returncode, stdout buffer and stderr buffer.
  17. Optionally prints stdout and stderr while running."""
  18. try:
  19. sub = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
  20. stdout, stderr = sub.communicate(input=input)
  21. returncode = sub.returncode
  22. if not silent:
  23. sys.stdout.write(stdout)
  24. sys.stderr.write(stderr)
  25. except OSError,e:
  26. if e.errno == 2:
  27. raise RuntimeError('"%s" is not present on this system' % cmdline[0])
  28. else:
  29. raise
  30. if returncode != 0:
  31. raise RuntimeError('Got return value %d while executing "%s", stderr output was:\n%s' % (returncode, " ".join(cmdline), stderr.rstrip("\n")))
  32. return stdout
  33. def human_dmesg():
  34. now = datetime.now()
  35. uptime_diff = None
  36. try:
  37. with open('/proc/uptime') as f:
  38. uptime_diff = f.read().strip().split()[0]
  39. except IndexError:
  40. return
  41. else:
  42. try:
  43. uptime = now - timedelta(seconds=int(uptime_diff.split('.')[0]), microseconds=int(uptime_diff.split('.')[1]))
  44. except IndexError:
  45. return
  46. dmesg_data = exec_process(['dmesg'], True)
  47. for line in dmesg_data.split('\n'):
  48. if not line:
  49. continue
  50. match = _dmesg_line_regex.match(line)
  51. if match:
  52. try:
  53. seconds = int(match.groupdict().get('time', '').split('.')[0])
  54. nanoseconds = int(match.groupdict().get('time', '').split('.')[1])
  55. microseconds = int(round(nanoseconds * 0.001))
  56. line = match.groupdict().get('line', '')
  57. t = uptime + timedelta(seconds=seconds, microseconds=microseconds)
  58. except IndexError:
  59. pass
  60. else:
  61. print "[%s]%s" % (t.strftime(_datetime_format), line)
  62. if __name__ == '__main__':
  63. human_dmesg()