Python 3 如何从标准输入上的文件生成 md5 哈希?

标签 python string buffer md5

我正在尝试使用 Python 3 从标准输入计算文件的 md5 哈希值

这是返回的错误信息。我不明白为什么它不返回 md5 哈希。任何帮助表示赞赏。

$./pymd5.py < tmp.pdf
Traceback (most recent call last):
  File "./pymd5.py", line 29, in <module>
    main()
  File "./pymd5.py", line 25, in main
    print(m.hexdigest())
TypeError: 'str' does not support the buffer interface
$ 

代码:

#!/usr/local/bin/python3.2

import sys
import hashlib

BUFSIZE = 4096

def make_streams_binary():
    sys.stdin  = sys.stdin.detach()
    sys.stdout = sys.stdout.detach()

def main():
    make_streams_binary()
    m = hashlib.md5()
    while True:
        data = sys.stdin.read(BUFSIZE)
        if not data:
            break
        m.update(data)

    print(m.hexdigest())

if __name__ == "__main__":
    main()

最佳答案

当你做的时候

sys.stdout = sys.stdout.detach()

它移除了在 Python 3 的终端上正常打印的能力,因为你 get a buffer instead of one wrapped for encoding and decoding .在您打印之前,您应该:

sys.stdout = sys._stdout

返回原来的stdout

关于Python 3 如何从标准输入上的文件生成 md5 哈希?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10202585/

相关文章:

python - 使用 Python 映射器的 Hadoop 流式处理的多个输出文件

java - 如何在 Java 中取消转义 HTML 字符实体?

python - 格式化字符串以 Python 方式使用 .format 进行 MySQL 查询

python - 反转字符串但将字符对放在一起

Vim:更改缓冲区编号

python - 使用 SequenceMatcher (Python) 生成内容差异

python - 按单个字符名称对列进行排序,元音在前

python - cookie 是一种通用且安全的 session 实现吗?

c++ - 如果找不到任何内容,Serial.find 是否会清除缓冲区

c++ - 将 uint8_t* 转换为 char* 以用于 QIODevice