微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Dart 中解码 ANSI 转义序列

如何解决在 Dart 中解码 ANSI 转义序列

我正在为面向 linux_x64 的 Flutter Desktop 编写一些代码
我正在从一些应用程序中提取一些日志,这些日志的语法如下:

  • 使用 less logfile

    检查日志文件
    ESC(BESC[mauthentication-msESC(BESC[m
    
    
  • 使用 less -r logfile 检查日志文件我可以在终端中看到彩色文本。

  • 使用 cat logfile 检查日志文件我可以在终端中看到彩色文本。

  • 使用 cat -vte logfile 检查日志文件我得到了这个:

    ^[(B^[[mauthentication-ms^[(B^[[m$
    
  • Flutter 中使用此代码

    Future<String> readAsstring = file.readAsstring();
    readAsstring.then((String value) => _log = utf8.decode(value.runes.toList()));
    

    我在 SelectableText 小部件中获得此输出

    (B[mauthentication-ms(B[m
    

我对这种行为真的很困惑,所以如果有人对此建议有经验,欢迎!

有两个选项:

  • 清理所有日志,可视化普通文本
  • 尝试像 less -r 一样解码文本,将彩色文本可视化到 Flutter 应用程序中。

编辑:解决了导入 tint plugin: tint: ^2.0.0

并更改 Dart 代码(使用 tint 插件中的 strip() 方法)如下:

Future<String> readAsstring = file.readAsstring();
readAsstring.then((String value) => _log = value.strip());

解决方法

那些有趣的字符被称为转义序列,程序使用它们来打印颜色和斜体等等。

终端旨在解码这些转义序列,但常规程序不知道如何处理它们。 lesscat 正在打印文件中的内容,是您运行它们的终端对它们进行解码。

你必须让你的程序通过这样的一段代码并删除所有的转义序列:

m = "h\x1b[34mello\x1b(A.\x1b[H" # Text full of random escape sequences
c = 0 # A count variable
p = True # Are we not in an escape sequence?
o = "" # The output variable
for l in m:
    if l == "\x1b":
        p = False
    elif p:
        o += l
    elif l in "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm": # Most (maybe all) escape sequences end in letters.
        p = True
    c += 1 # Move on to the next letter in the input string
    
print(o) # Text without escape sequences

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。