端子输出的安全逃逸功能 [英] Safe escape function for terminal output

查看:125
本文介绍了端子输出的安全逃逸功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找相当于 urlencode 的终端输出 - 我需要确保垃圾字符I(可能)从外部源打印不会最终对我的终端做好玩的事情,所以预先包装的功能来转义特殊字符序列将是理想的。

I'm looking for the equivalent of a urlencode for terminal output -- I need to make sure that garbage characters I (may) print from an external source don't end up doing funky things to my terminal, so a prepackaged function to escape special character sequences would be ideal.

我在Python中工作,但任何我都可以轻松翻译的作品。 TIA!

I'm working in Python, but anything I can readily translate works too. TIA!

推荐答案


$ ./command | cat -v

$ cat --help | grep nonprinting
-v, --show-nonprinting   use ^ and M- notation, except for LFD and TAB

这是基于 android / cat.c

#!/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"print map chr,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 

它打印:


Files cat-v.out and python.out are identical

这篇关于端子输出的安全逃逸功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆