Skip to content

Instantly share code, notes, and snippets.

@saghul
Created August 21, 2010 20:00
Show Gist options
  • Save saghul/542780 to your computer and use it in GitHub Desktop.
Save saghul/542780 to your computer and use it in GitHub Desktop.
pydmesg: dmesg with human readable timestamps
#!/usr/bin/env python
# coding=utf8
# Copyright (C) 2010 Saúl ibarra Corretgé <[email protected]>
#
"""
pydmesg: dmesg with human-readable timestamps
"""
from __future__ import with_statement
import re
import subprocess
import sys
from datetime import datetime, timedelta
_datetime_format = "%Y-%m-%d %H:%M:%S"
_dmesg_line_regex = re.compile("^\[\s*(?P<time>\d+\.\d+)\](?P<line>.*)$")
def exec_process(cmdline, silent, input=None, **kwargs):
"""Execute a subprocess and returns the returncode, stdout buffer and stderr buffer.
Optionally prints stdout and stderr while running."""
try:
sub = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
stdout, stderr = sub.communicate(input=input)
returncode = sub.returncode
if not silent:
sys.stdout.write(stdout)
sys.stderr.write(stderr)
except OSError,e:
if e.errno == 2:
raise RuntimeError('"%s" is not present on this system' % cmdline[0])
else:
raise
if returncode != 0:
raise RuntimeError('Got return value %d while executing "%s", stderr output was:\n%s' % (returncode, " ".join(cmdline), stderr.rstrip("\n")))
return stdout
def human_dmesg():
now = datetime.now()
uptime_diff = None
try:
with open('/proc/uptime') as f:
uptime_diff = f.read().strip().split()[0]
except IndexError:
return
else:
try:
uptime = now - timedelta(seconds=int(uptime_diff.split('.')[0]), microseconds=int(uptime_diff.split('.')[1]))
except IndexError:
return
dmesg_data = exec_process(['dmesg'], True)
for line in dmesg_data.split('\n'):
if not line:
continue
match = _dmesg_line_regex.match(line)
if match:
try:
seconds = int(match.groupdict().get('time', '').split('.')[0])
nanoseconds = int(match.groupdict().get('time', '').split('.')[1])
microseconds = int(round(nanoseconds * 0.001))
line = match.groupdict().get('line', '')
t = uptime + timedelta(seconds=seconds, microseconds=microseconds)
except IndexError:
pass
else:
print "[%s]%s" % (t.strftime(_datetime_format), line)
if __name__ == '__main__':
human_dmesg()
@aboyett
Copy link

aboyett commented Mar 13, 2012

What license do you place this code under? I was going to implement similar functionality when I ran across your blog posting and this gist.

@saghul
Copy link
Author

saghul commented Mar 13, 2012

The code has been put on the public domain, so you may use it however you want :-)

@dopuskh3
Copy link

There is a bug in regex. Corrected in https://gist.github.com/9908ac6b31133eb54331

@saghul
Copy link
Author

saghul commented May 16, 2012

@dopuskh3 Fixed it, thanks!

@i-rinat
Copy link

i-rinat commented Jan 17, 2019

Since about July 2011 one can use dmesg -T or dmesg --ctime to get human-readable timestamps.

@antdude
Copy link

antdude commented May 21, 2020

Thanks. :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment