【问题标题】:How to read from byte object in Python如何在 Python 中读取字节对象
【发布时间】:2021-07-22 15:34:42
【问题描述】:

我可以使用 subprocess.run 即时成功地 tar 文件,但由于以下错误,我无法使用 send_file 选项发送 tar 文件:

AttributeError: 'bytes' object has no attribute 'read'

使用subprocess.Popen,我能够成功地压缩和发送小文件(几乎不超过 1GB)。但是使用subprocess.Popen 压缩最大 4GB 的文件时会出现问题,因为 subprocess.Popen 正在使用内存到 tar。

所以我已移至 subprocess.run...但是由于上述错误而失败。

请找代码sn-p:

process = subprocess.run(['tar', '-cvf', '-', test_dir], stdout=subprocess.PIPE)
send_file(process.stdout, as_attachment=True, attachment_filename=test_dir.tar)

send_file 来自烧瓶框架。

对于上述内容的任何帮助将不胜感激。

【问题讨论】:

    标签: python subprocess


    【解决方案1】:

    AttributeError: 'bytes' object has no attribute 'read

    这种.read 的平均能力是预期的,因为您已经拥有bytes,它应该足以像这样使用来自io 内置模块的io.BytesIO

    import io
    

    ...

    process = subprocess.run(['tar', '-cvf', '-', test_dir], stdout=subprocess.PIPE)
    data = process.stdout
    send_file(io.BytesIO(data), as_attachment=True, attachment_filename=test_dir.tar)
    

    【讨论】:

    • 感谢您的及时回复,我使用了 Bytes.IO 但它返回 0 字节,即空 tar 文件 请查找更新后的代码 sn-p: buffer = io.BytesIO() buffer.write( process.stdout) response = send_file(buffer, as_attachment=True, attachment_filename=f'{base_dir}.tar') 请建议如何进一步处理。
    • @GiriVarshini 如果你使用io.BytesIO这种方式你需要在写完后寻求启动;在 send_file( 之前添加 buffer.seek(0)...
    • 我使用了 buffer.seek(0) 但它仅适用于 4Gb 以上的大文件的小 tar 文件,此过程不起作用。请建议使用 send_file 选项发送大文件的任何其他解决方案。在此先感谢:)
    • @GiriVarshini 您可以尝试:让tar 创建文件,然后在 python 中使用open 并将创建的文件句柄提供给send_file。然后应该删除这个文件,但我不知道如何确保它不会被过早删除
    猜你喜欢
    • 2020-01-23
    • 2023-01-20
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 2018-01-08
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    相关资源
    最近更新 更多