Categories
Python Answers

How to tail a log file in Python?

Spread the love

Sometimes, we want to tail a log file in Python.

In this article, we’ll look at how to tail a log file in Python.

How to tail a log file in Python?

To tail a log file in Python, we can use the sh library.

To install it, we run

pip install sh

For instance, we write

from sh import tail

for line in tail("-f", "/var/log/some_log_file.log", _iter=True):
    print(line)

to call tail with the options for tail and the file we want to run tail for.

And we set _iter to True to return a generator that returns new content whenever the file is updated.

Then we use a for loop to loop through the lines and print them.

Conclusion

To tail a log file in Python, we can use the sh library.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *