2

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

我在 Python 中工作,但我可以轻松翻译的任何东西也可以。蒂亚!

4

4 回答 4

3

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

于 2009-01-12T23:49:53.880 回答
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 是相同的
于 2009-01-13T00:09:29.443 回答
1

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

x = get_weird_data()
print repr(x)
于 2009-01-13T21:38:22.523 回答
-1

你可以通过字符串管道它

./command | strings

这将去除非字符串字符

于 2009-01-12T23:40:17.207 回答