2
0

pydmesg 2.3 KB

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