• 技术文章 >后端开发 >Python教程

    怎么使用Python3实时操作处理日志文件

    PHPzPHPz2023-04-20 15:01:06转载31

    一、简单的实时文件处理(单一文件)

    假设我们要实时读取的日志的路径为: /data/mongodb/shard1/log/pg.csv

    那么我们可以在python文件中使用shell脚本命令tail -F 进行实时读取并操作

    代码如下:

    import re
    import codecs
    import subprocess
     
    def pg_data_to_elk():
        p = subprocess.Popen('tail -F /data/mongodb/shard1/log/pg.csv', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,)    #起一个进程,执行shell命令
        while True:
            line = p.stdout.readline()   #实时获取行
            if line:                     #如果行存在的话
                xxxxxxxxxxxx
                your operation

    简单解释一下subprocess模块:

    subprocess允许你生成新的进程,连接到它们的 input/output/error 管道,并获取它们的返回(状态)码。

    subprocess.Popen介绍

    该类用于在一个新的进程中执行一个子程序。

    subprocess.Popen的构造函数

    class subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, 
        preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False,
        startup_info=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=())

    参数说明:

    二、复杂的实时文件处理(不断产生新文件)

    如果日志会在满足一定条件下产生新的日志文件,比如log1.csv已经到了20M,那么则会写入log2.csv,这样一天下来大概有1000多个文件,且不断产生新的,那么如何进行实时获取呢?

    思路如下:

    在实时监听(tail -F)中加入当前文件的大小判定,如果当前文件大小大于20M,那么跳出实时监听,获取新的日志文件。(如果有其他判定条件也是这个思路,只不过把当前文件大小的判定换成你所需要的判定)

    代码如下:

    import re
    import os
    import time
    import codecs
    import subprocess
    from datetime import datetime
     
    path = '/home/liao/python/csv'
    time_now_day = datetime.now.strftime('%Y-%m-%d')
     
    def get_file_size(new_file):
        fsize = os.path.getsize(new_file)
        fsize = fsize/float(1024*1024)
        return fsize
     
    def get_the_new_file():
        files = os.listdir(path)
        files_list = list(filter(lambda x:x[-4:]=='.csv' and x[11:21]==time_now_day, files))
        files_list.sort(key=lambda fn:os.path.getmtime(path + '/' + fn) if not os.path.isdir(path + '/' + fn) else 0)
        new_file = os.path.join(path, files_list[-1])
        return new_file
     
    def pg_data_to_elk():
        while True:
            new_file = get_the_new_file()
            p = subprocess.Popen('tail -F {0}'.format(new_file), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,)    #起一个进程,执行shell命令
            while True:
                line = p.stdout.readline()   #实时获取行
                if line:                     #如果行存在的话
                    if get_file_size(new_file) > 20:    #如果大于20M,则跳出循环
                        break
                    xxxxxxxxxxxx
                    your operation
            time.sleep(3)

    以上就是怎么使用Python3实时操作处理日志文件的详细内容,更多请关注php中文网其它相关文章!

    声明:本文转载于:亿速云,如有侵犯,请联系admin@php.cn删除
    专题推荐:Python
    上一篇:python中强制关闭线程、协程与进程的方法是什么 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • 如何使用Python自动化生成PDF报告?• Python协程的实现方法有哪些?• 如何解决Python中出现File "<stdin>", line 1非语法错误• Python中类型提示的最佳实践• Python如何获取本机内网IP地址
    1/1

    PHP中文网