【问题标题】:How to read sys.stdin containing binary data in python (ignore errors)?如何在python中读取包含二进制数据的sys.stdin(忽略错误)?
【发布时间】:2022-08-15 00:20:16
【问题描述】:

如何阅读sys.stdin,但忽略解码错误? 我知道sys.stdin.buffer 存在,我可以读取二进制数据,然后用.decode(\'utf8\', errors=\'ignore\') 对其进行解码,但我想逐行读取sys.stdin。 也许我可以以某种方式重新打开sys.stdin 文件但使用errors=\'ignore\' 选项?

  • 将解码放在 try 中并将解码错误作为异常处理怎么样?
  • @SembeiNorimaki,它有什么帮助?我需要做sys.stdin.read(),或者更具体地说是for line in sys.stdin,但它会抛出一个UnicodeDecodeError。如果我抓住它,我怎么能读到这条线?我只需要忽略它无法读取的符号。该行主要包含 ascii 字符,但它可以包含 ASCII 之外的字符,所以我需要忽略它们或替换为 \'?\' 例如
  • 如果你不能解码它,你必须看看为什么。给我们一个给出解码错误的输入示例。也许有些输入是以另一种格式编码的,我们需要一些例子来看看如何解决它
  • @SembeiNorimaki,数据无所谓,我想期待任何数据,包括纯二进制数据(甚至经常是文本),我不想能够解码所有数据,我想成为能够忽略我无法使用bytes.decode 函数解码的数据。如果我正在读取像open(filename, \'r\', errors=\'ignore\') 这样的实际文件,我可以这样做,但我想改为读取sys.stdin,但它已经是一个打开的文件描述符,所以我不知道如何设置errors=\'ignore\'选项。
  • 然后你放一个try并在里面解码数据和一个except和一个pass,它将忽略无法解码的数据

标签: python file encoding stdin


【解决方案1】:

您可以在PYTHONIOENCODING 环境变量上设置错误处理程序选项:这将影响sys.stdinsys,stdoutsys.stderr 将始终使用“反斜杠替换”)。 PYTHONIOENCODING 接受可选的编码名称和可选的错误处理程序名称,前面有冒号,因此“UTF8”、“UTF8:ignore”和“:ignore”都是有效值。

$  cat so73335410.py
import sys

if __name__ == '__main__':
    data = sys.stdin.read()
    print(data)
$
$  echo hello | python so73335410.py
hello

$  echo hello hello hello hello | zip > hello.zip
  adding: - (deflated 54%)
$
$  cat hello.zip | PYTHONIOENCODING=UTF8:ignore python so73335410.py
UYv>
  -▒
UY  HW@'PKv>

  ▒-PK,-/>PKmPK/>
$ 

【讨论】:

    猜你喜欢
    • 2011-07-26
    • 2017-07-10
    • 2016-03-08
    • 2010-12-08
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    相关资源
    最近更新 更多