代码之家  ›  专栏  ›  技术社区  ›  Senthil Kumaran

使用cat/ansifilter或任何其他工具从日志文件中删除ansi转义输出[关闭]

  •  -2
  • Senthil Kumaran  · 技术社区  · 5 月前

    我有kubernetes一致性测试的输出。

    \u001b[90mtest/e2e/common/network/framework.go:23\u001b[0m
      Granular Checks: Pods
      \u001b[90mtest/e2e/common/network/networking.go:32\u001b[0m
        should function for intra-pod communication: udp [NodeConformance] [Conformance]
        \u001b[90mtest/e2e/framework/framework.go:652\u001b[0m
    \u001b[90m------------------------------\u001b[0m
    

    我想读取输出,删除所有转义序列。我无法控制代码,所以我对cat、less-r、ansifilter等有感觉;甚至sed。

    但这些都没有帮助我删除逃跑序列。我该如何删除这些?

    2 回复  |  直到 5 月前
        1
  •  2
  •   Fravadona    5 月前

    CSI(控制序列导入器)序列

    对于控制序列导入器或CSI命令 ESC [ (写成 \e[ \033[ 在几种编程语言中)后面是0x300x3F(ASCII)范围内的任何数量(包括无)的“参数字节” 0–9:;<=>? ),然后乘以该范围内的任意数量的“中间字节” 0x20–0x2F (ASCII空格和 !"#$%&'()*+,-./ ),然后最后是0x400x7E(ASCII)范围内的单个“最后一个字节” @A–Z[\]^_`a–z{|}~ ).

    因此,用于删除它们的POSIX解决方案可以是:

    LANG=C awk '1+gsub(/\033\[[0-?]*[ -\/]*[@-~]/,"")'
    

    编辑

    作为 ESC CSI中的JSON似乎是转义的,那么你可以使用:

    LANG=C awk '1+gsub(/\\u001[bB]\[[0-?]*[ -\/]*[@-~]/,"")'
    
        2
  •  0
  •   Senthil Kumaran    5 月前

    唯一对我有效的解决方案是这个片段。

    import re
    import sys
    
    output_file = sys.argv[1]
    print(output_file)
    
    def remove_escapes(text):
        # First, replace Unicode escape sequences
        text = text.encode('ascii', 'ignore').decode('unicode_escape')
    
        # Then, remove ANSI escape sequences
        ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
        return ansi_escape.sub('', text)
    
    
    for line in open(output_file):
        try:
    
            parsed_line = remove_escapes(line)
        except UnicodeDecodeError:
            print("UnicodeDecodeError: " + line)
            continue
        print(parsed_line, end='')