迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Python - 尾部日志文件并比较阻塞和非阻塞尾部函数

作者:迹忆客 最近更新:2023/06/26 浏览次数:

本篇文章概述了 Python 中的 tail() 函数,介绍了它的工作原理并演示了如何尾部日志文件。

它还比较了 Python 的阻塞和非阻塞尾部函数并强调了差异。


Python tail() 函数概述

在 Python 中,使用 tail() 函数时默认显示数据框的最后五行。 只有一个输入参数,即行数。

此选项允许我们显示特定数量的行。 此外,tail() 函数还接受负数,如下例所示。

在这种情况下,将返回所有行,但不返回第一行。 head()tail() 之间的主要区别在于,当传递空参数时,head()tail() 都返回五行。

请记住,head()tail() 函数生成有序数据,而 sample() 生成无序数据。

tail() 函数的语法:

dataframe.tail(n=5)

Python 中 Tail() 函数的工作原理

如果我们将 n 的负值传递给 tail() 函数,它将排除第一个 n (请参见以下示例)。

当我们运行 print(df.tail(2)) 时,它显示最后两行,当我们执行 print(df.tail(-6)) 时,它显示除前 6 行之外的所有行。

示例代码:

import pandas as pd
df = pd.DataFrame({'Colours': ['Purple', 'White', 'Black', 'Brown',
                'Pink', 'Orange', 'Blue', 'Red', 'Yellow']})
print("Complete Data Frame:")
print(df)

print("When we pass the value of `n`:")
print(df.tail(2))

print("\nWhen we pass the -ve value of `n`:")
print(df.tail(-6))

输出:

Complete Data Frame:
   Colours
0  Purple
1   White
2   Black
3   Brown
4    Pink
5  Orange
6    Blue
7     Red
8  Yellow

When we pass the value of `n`:
   Colours
7     Red
8  Yellow

When we pass the -ve value of `n`:
   Colours
6    Blue
7     Red
8  Yellow

用 Python 跟踪日志文件

我们创建了一个名为 std.log 的日志文件,在其中存储了一些数据,我们将在下面的输出中看到这些数据。 要跟踪日志文件,我们可以从 sh 模块运行 tail。

为了执行无限循环并显示输出行,我们调用 tail(),并将文件名和 _iter 设置为 True。

示例代码:

from sh import tail

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

输出:

2022-08-25 21:44:10,045 This is just a reminder
2022-08-25 21:44:10,046 Meeting is at 2 pm
2022-08-25 21:44:10,046 After the lunch break

请记住,文档说 sh 仅在类似 Linux 的操作系统上受支持。 值得注意的是,不支持 Windows。


Python 中的阻塞与非阻塞 Tail() 函数

让我们从非阻塞 tail() 函数开始。

非阻塞 Tail() 函数

当某个功能被阻止时,它可能会推迟后续活动的完成。 此外,我们可能会影响系统的整体性能。

换句话说,您的程序将阻止并阻止其他任何程序运行。 为了启动子进程并连接到其输出流,我们使用子进程模块(stdout)。

示例代码:

import subprocess
import select
import time

f = subprocess.Popen(['tail','-F',"log.txt"],
        stdout=subprocess.PIPE,stderr=subprocess.PIPE)
p = select.poll()
p.register(f.stdout)

while True:
    if p.poll(1):
        print(f.stdout.readline())
    time.sleep(1)

输出:

b'2022-08-25 21:44:10,045 This is just a reminder\n'

阻塞 Tail() 函数

以下代码还将在添加新行时显示它们,但您可以使用 subprocess 模块而无需额外的 select 模块调用。 它会阻塞,直到使用 f.kill() 命令终止 tail 程序。

示例代码:

import subprocess
f = subprocess.Popen(['tail','-F',"log.txt"],
        stdout=subprocess.PIPE,stderr=subprocess.PIPE)
while True:
    line = f.stdout.readline()
    print(line)

输出:

b'2022-08-25 21:44:10,045 This is just a reminder\\n'
b'2022-08-25 21:44:10,046 Meeting is at 2 pm\\n'

上述示例的日志文件

以下代码用于创建 log.txt,然后在阻塞和非阻塞代码中使用它。

示例代码:

import logging
logging.basicConfig(filename="log.txt", level=logging.DEBUG,
                    format="%(asctime)s %(message)s")
logging.debug("This is just a reminder")
logging.info("Meeting is at 2 pm")
logging.info("After the lunch break")

输出:

2022-08-25 21:44:10,045 This is just a reminder
2022-08-25 21:44:10,046 Meeting is at 2 pm
2022-08-25 21:44:10,046 After the lunch break

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便