python-3.x - Python 3 优雅的方式将二进制输出打印到终端

标签 python-3.x

我写了一个小脚本,它基本上在 Windows 终端(使用希腊语 cp737 代码页)打印一些信息。它本质上是这样的:

while True:
    title = u'greek and other unichars follow:\t{}'.format(unicode_input())
    print title.encode('cp737','ignore')

输出:
greek and other unichars follow:    Καλημέρα!

它按预期工作,终端打印大部分希腊字母并忽略无法转换为更受约束的 cp737 的罕见异常。

现在在 python3 中打印字节时,如 u"unitext".encode(),将字节对象“原样”输出到标准输出:
b"greek and other unichars follow:\t\x89\x98\xa2\x9e\xa3\xe2\xa8\x98!"
  • 在终端中直接打印 unicode 最终会导致
    Unicode 编码错误。
  • 转换 unicode -> bytes(cp737,ignore) -> unicode,看起来很古怪。

  • 那么这样做的优雅方式是什么?

    最佳答案

    对于 Python 3,您有几个可用选项:

  • 设置 PYTHONIOENCODING终端编码的环境变量。例如,您可以将其设置为 PYTHONIOENCODING=cp737:ignore .然后,如果您使用 print 打印 Unicode 文本,它会自动转换为 cp737字符集和输出正确。
  • 重置您的 sys.stdout 的编码在运行时。看到这个问题:How to set sys.stdout encoding in Python 3?
  • 将编码后的字节直接写入 sys.stdout.buffer ,它绕过了 sys.stdout 使用的编码机制.
  • 关于python-3.x - Python 3 优雅的方式将二进制输出打印到终端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24152761/

    相关文章:

    python - 我的脚本中处理器的使用情况可笑。如何优化呢?

    python - 从迭代中生成多行字符串

    python - 将单个模块添加到 Python 的导入搜索路径?

    python - 如何找到匹配的字节码?

    python - 对于相同大小的列表,为什么深复制比浅复制慢得多?

    python - cv2.matchTemplate 在图像中发现错误的模板

    python - 如何使用多处理来加速以下功能?

    python - 使用来自 PyQt5 循环的项目刷新 QTableView 的内容

    python - pyparsing 优先级分割

    linux - 如何通过套接字将 `eof` 信号发送到在远程 shell 中运行的命令?