【问题标题】:Safe escape function for terminal output终端输出安全逃生功能
【发布时间】:2010-10-01 01:12:15
【问题描述】:

我正在寻找与urlencode 等效的终端输出——我需要确保我(可能)从外部源打印的垃圾字符不会最终对我的终端做一些时髦的事情,所以一个用于转义特殊字符序列的预打包函数将是理想的。

我正在使用 Python,但我可以轻松翻译的任何内容也可以。蒂亚!

【问题讨论】:

    标签: python terminal escaping


    【解决方案1】:

    不幸的是,“终端输出”是一个非常不明确的过滤标准(请参阅question 418176)。我建议简单地将您想要允许的字符列入白名单(这将是大多数 string.printable),并用您喜欢的任何转义格式(\FF、%FF 等)替换所有其他字符,或者甚至简单地将它们剥离。

    【讨论】:

      【解决方案2】:
      $ ./命令 |猫-v $ 猫--帮助 | grep 非打印 -v、--show-nonprinting 使用 ^ 和 M- 表示法,LFD 和 TAB 除外

      这里是基于android/cat.c的py3k中的相同:

      #!/usr/bin/env python3
      """Emulate `cat -v` behaviour.
      
      use ^ and M- notation, except for LFD and TAB
      
      NOTE: python exits on ^Z in stdin on Windows
      NOTE: newlines handling skewed towards interactive terminal. 
            Particularly, applying the conversion twice might *not* be a no-op
      """
      import fileinput, sys
      
      def escape(bytes):
          for b in bytes:
              assert 0 <= b < 0x100
      
              if  b in (0x09, 0x0a): # '\t\n' 
                  yield b
                  continue
      
              if  b > 0x7f: # not ascii
                  yield 0x4d # 'M'
                  yield 0x2d # '-'
                  b &= 0x7f
      
              if  b < 0x20: # control char
                  yield 0x5e # '^'
                  b |= 0x40
              elif  b == 0x7f:
                  yield 0x5e # '^'
                  yield 0x3f # '?'
                  continue
      
              yield b
      
      if __name__ == '__main__':
          write_bytes = sys.stdout.buffer.write 
          for bytes in fileinput.input(mode="rb"):
              write_bytes(escape(bytes))
      

      例子:

      $ perl -e"打印地图字符,0..0xff" > bytes.bin $ cat -v bytes.bin > cat-v.out $ python30 cat-v.py bytes.bin > python.out $ diff -s cat-v.out python.out

      打印出来:

      文件 cat-v.out 和 python.out 是相同的

      【讨论】:

      • 非常好,感谢您移植/指出实现。
      【解决方案3】:

      如果记录或打印调试输出,我通常使用repr() 来获取对象的无害可打印版本,包括字符串。这可能是也可能不是您想要的;其他人在其他答案中使用的cat --show-nonprinting 方法更适合大量多行输出。

      x = get_weird_data()
      print repr(x)
      

      【讨论】:

        【解决方案4】:

        你可以通过字符串管道它

        ./command | strings
        

        这将去除非字符串字符

        【讨论】:

        • 我仍然想显示字符,但不会对终端本身造成副作用。不过,这是一个不错的备用计划!
        猜你喜欢
        • 2011-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-24
        • 2022-06-13
        • 1970-01-01
        • 2015-11-06
        相关资源
        最近更新 更多