【问题标题】:Is there a way in python to tail a file and work with the line-output [duplicate]python中有没有办法尾随文件并使用行输出[重复]
【发布时间】:2018-04-27 12:08:34
【问题描述】:

我正在编写一个尾随日志文件的简短脚本。应该可以使用正则表达式过滤输出,并在必要时按 /t 分割。

几年前我在perl中写过类似的东西,但必须将其更改为python

perl 代码片段:

open(FILE,"tail -F logfile | grep -v something | ");
while(<FILE>){
    my @lineparts = split(/\t/,$_);
    ...
    do something else
    ...
}

我已经尝试过 Popen 不同的品种(logger.sh 在远程服务器上通过 ssh 包含 tail -F)

cmd = subprocess.Popen("./logger.sh").communicate()
for line in cmd.stdout.readline(): 
    test = line

    if re.match('.*ERR.*', test):
        print "ERROR"

但我得到的只是标准输出上的输出,我无法操作它(从未打印过“错误”)

有人有什么想法吗?

【问题讨论】:

    标签: python


    【解决方案1】:

    我无法使用正则表达式,因为您没有发布日志文件外观的示例。我可以帮助处理文件的尾部,因为这是非常普遍的。

    data = []
    with open(logfile,'rt',encoding='utf-8')as infile:
        for i,e in enumerate(infile):
            data.append(e.strip())
        if i < 11:
            for line in data:
                print(line)
        else:
            for line in data[:-10]:
                print(line)
    

    在您的情况下,您会将“打印”保存到容器中,然后针对它运行您的正则表达式。

    【讨论】:

    • 谢谢,像魅力一样工作
    • @PeterSander 你会考虑投票和接受作为答案吗? ^_^
    • 我的错,忘了
    猜你喜欢
    • 1970-01-01
    • 2020-12-26
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 2021-02-09
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多