Update monitoring of dmesg (/ dev / kmsg) from python on Linux

A sample implementation that monitors the logs that can be confirmed with dmesg, such as tail -F, for tail updates. The ring buffer output by dmesg can be opened as a file by / dev / kmsg or / proc / kmsg. Since it blocks with read on the last line, ʻO_NONBLOCK` is specified only when skipping is processed.

Implementation

dmesg(/dev/kmsg)Update monitoring


#!/usr/bin/env python2
# cofing: UTF-8

import os
import fcntl
import time

def readLines(path):
    with open(path, "r") as fp:
        stat = os.stat(path)
        fp.seek(stat[6])

        where = None

        # =================
        # seek to last line
        # =================
        fd   = fp.fileno()
        flag = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, flag | os.O_NONBLOCK)

        try:
            # FIXME
            for last in fp:
                pass
        except IOError as e:
            if e.errno != 11:
                raise

        fcntl.fcntl(fd, fcntl.F_SETFL, flag)

        # =================
        # tailf impl
        # =================
        try:
            while True:
                where = fp.tell()
                line  = fp.readline()
                yield line
        except KeyboardInterrupt:
            pass

if __name__ == "__main__":
    import sys
    for line in readLines("/dev/kmsg"):
        if str(line).find("stop tailf") >= 0:
            print "### stop watch tailf ###"
            break
        else:
            print line,

The execution and its result are as follows.

Execution result and end(Monitoring side)


$ ./tailf.py
12,642,9584294872,-;aaa
12,643,9588998703,-;bbb
12,644,9593362017,-;ccc
### stop watch tailf ###

By redirecting to / dev / kmsg, the output of the driver log is confirmed in a pseudo manner.

Execution result and end(Update side sample)


$ sudo sh -c "echo aaa > /dev/kmsg"
$ sudo sh -c "echo bbb > /dev/kmsg"
$ sudo sh -c "echo ccc > /dev/kmsg"
$ sudo sh -c "echo stop tailf > /dev/kmsg"

TODO

I didn't know a good way to seek to the last line of the file in python, so I implemented it by reading everything up to the last line. In the case of a huge file, it may take a long time just to skip it. (When changing the size of the ring buffer, etc.)

# FIXME
for last in fp:
    pass

reference

Emerge Technology: Tail-like with Python Output the line containing the specified character string from the text file --Qiita python - What is the most efficient way to get first and last line of a text file? - Stack Overflow Get last n lines of a file with Python, similar to tail - Stack Overflow python Non-block read file - Stack Overflow

Recommended Posts

Update monitoring of dmesg (/ dev / kmsg) from python on Linux
Update Python on Mac from 2 to 3
At the time of python update on ubuntu
Update vscode on linux
Put the latest version of Python on linux (Debian) on Chromebook
Automatic update of Python module
Handling of python on mac
Update python on Mac to 3.7-> 3.8
Real-time display of video acquired from webcam on Jupyter notebook (Python3)
[Python] Get the update date of a news article from HTML
Installation from python, numpy, scipy sources without root privileges on Linux
How to update the python version of Cloud Shell on GCP
Install Python Pillow on Amazon Linux
Notes on using MeCab from Python
Completion of docker command on Linux
Environment construction of python3.8 on mac
Notes on accessing dashDB from python
Introduce Python 3.5.2 environment on Amazon Linux
python> os.path.join ('data','checkpoint')>'data / checkpoint' on linux
Call C / C ++ from Python on Mac
Data integration from Python app on Linux to Amazon Redshift with ODBC
Run a batch of Python 2.7 with nohup on Amazon Linux AMI on EC2
From re-environment construction of Python to graph drawing (on visual studio code)
Get keystrokes from / dev / input (python evdev)
How to update Google Sheets from Python
Learning notes from the beginning of Python 1
Clogged with python update of GCP console ①
[C] [python] Read with AquesTalk on Linux
How to update php on Amazon linux 2
Basic usage of Btrfs on Arch Linux
Connecting from python to MySQL on CentOS 6.4
How to update security on CentOS Linux 8
Study on Tokyo Rent Using Python (3-1 of 3)
[Amazon Linux] Switching from Python 2 series to Python 3 series
[Python] Japanese localization of matplotlib on Ubuntu
Learning notes from the beginning of Python 2
Install Python 3.8, Pip 3.8 on EC2 (Amazon Linux 2)
Linux "Install on / dev / sda" error resolution