如何从 python 子进程的输出中剥离和删除特殊字符

How to strip and removed special characters from the out put of python sub process

我正在使用 Python 子进程来执行命令,如下所示:

process = subprocess.Popen(['debug', 'file.tgz'], 
                           stdout=subprocess.PIPE,stderr=subprocess.PIPE)


while True:
    output = process.stdout.readline()
    print(str(output.strip()).encode())
    return_code = process.poll()

    if return_code is not None:
         break 

我输出的内容如下图:

b"b'Registers:'"

这就是我所期待的。

Registers:

我正在使用编码,但仍然看到相同的输出。如果我 运行 在命令行上执行相同的进程,我将得到相同的期望输出。

如何删除这些特殊字符?

  • 跳过 str();这将摆脱内部 b'...'
  • 您想要 .decode 而不是 .encode,因为您想要将 byte-stream(来自子进程)转换为字符串(用于打印)。您需要知道它使用的是哪种编码,以及(如果适用)如何处理格式错误的数据。
  • (可选)在解码之后去除空白,而不是之前,同时去除 non-ASCII 个空白字符(如果有的话)。
    print(output.decode('utf8', errors='strict').strip())